Instance methods vs. functions and the self parameter

Alex Martelli aleax at aleax.it
Sun Feb 2 09:28:22 EST 2003


Henrik Hansen wrote:
   ...
>  >>> class Class:
>          def method(self):
>              print "I have a self!"
> 
>  >>> def function():
>          print "I don't..."
> 
>  >>> instance = Class()
>  >>> instance.method()
> I have a self!
>  >>> instance.method = function
>  >>> instance.method()
> I don't...
> 
> </example>
> 
> Ok, so I understand that you can assign instance.method to function, but
> what about the self argument? As I understand it, when calling a method
> like this: foo.bar() would be equivalent to calling like this (assuming
> that foo is an instance of class Baz): Baz.bar(foo). Is that correct?

Yes.

> In other words, why doesn't the function need to be declared
> function(self): ..., since it receives a parameter?

Because functions are mutated into methods only when accessed
*THROUGH THE CLASS OBJECT* (directly, or indirectly through
the instance oblect delegating to the class object).  There
is no such mutation when functions are accessed directly through
the instance object.  Check this:


class Class:
    def method(self):
        print "I have a self!"

def function():
    print "I don't..."

instance = Class()
print instance.method
instance.method = function
print instance.method

[alex at lancelot probnut]$ python b.py
<bound method Class.method of <__main__.Class instance at 0x401bc08c>>
<function function at 0x401a34c4>

See the difference?  In the first case, instance has no
per-instance attribute named 'method', so it delegates the
lookup up to Class -- and since the lookup happens through
Class, the function IS transformed into a methos (more
specifically a bound method, since the lookup is _on_ an
instance even though it goes _through_ the class).  In
the second case, instance DOES have the requested
per-instance attribute, so it responds directly -- the
function object remains a function object, no mutation.


Alex






More information about the Python-list mailing list