odd difference calling function from class or instance variable

2014-08-13 Thread GregS

Hello,

This is my first post here so please gently inform me of any etiquette 
breaches.


I'm seeing a behaviour I can't explain with Python 3.4.1 when I call a 
function via a reference stored in an object.


When I assign the reference as a class variable, the reference has 
__self__ set, too, so I get an extra argument passed to the function.  
If I assign the reference as an instance variable, then __self__ is 
unset so no extra argument.


Here's what I mean:


def print_args(*args):

print(args)


class C:

ref = None


C.ref = print_args# assign to class variable
i = C()
i.ref() # call via class variable - get a 'self' argument passed

(<__main__.C object at 0x1071a05f8>,)

i.ref = print_args   # assign to instance variable
i.ref() # call via instance variable: no arguments

()

If you look at i.ref.__self__ for the two cases, you'll see what's 
going on.  I've tried RTFMing but can't find the reason for the two 
behaviours.  Could someone provide an explanation for me, please?


Thanks,

Greg


--
https://mail.python.org/mailman/listinfo/python-list


Re: odd difference calling function from class or instance variable

2014-08-13 Thread GregS
Thanks to both of you for your incredibly prompt replies.  My homework 
for tonight is to digest the descriptor protocol...


Peter, thanks for suggesting using staticmethod() to get the behaviour 
I was expecting.  I've only used staticmethod as a decorator before now.


Chris, I agree that it's not every day you assign functions to class 
attributes, but it does have its uses (I won't bore you with mine).  
Now that I know how it treads on the toes of Python's method magic, I 
can decide whether it's the best approach or not.


Thanks again,

Greg



--
https://mail.python.org/mailman/listinfo/python-list