Promoting Python

Marko Rauhamaa marko at pacujo.net
Thu Apr 7 02:30:58 EDT 2016


Rolf Camps <rolf at roce.be>:

> Op 07-04-16 om 00:03 schreef Marko Rauhamaa:
>> IOW, if I have this class:
>>
>>      class A:
>>          def f(self):
>>              print("f")
>>
>> and this object:
>>
>>      a = A()
>>
>> then,
>>
>>      a.f
>>
>> is a function that doesn't have a self argument. That function is
>> generated on the fly, and it delegates to A.f, providing it with self
>> argument.
> a.f is not a function, A.f is a function.
> a.f is an instance method. The function is not generated on the fly,
> when the method is called, it calls the function A.f with an extra
> argument __self__ (the instance a) inserted before the argument list the
> instance method was called with.

What you call an instance method *is* a function, meaning it is bound to
a callable object that in almost no outward way differs from any other
function.

It is generated on the fly:

   >>> id(a.f)
   140059683793288
   >>> id(a.f)
   140059683793864
   >>> a.f is a.f
   False

You are correct that the generated function is a simple trampoline that
supplies a self argument and delegates to A.f.

Or:

   When a class attribute reference (for class C, say) would yield a
   class method object, it is transformed into an instance method object
   whose __self__ attributes is C.
   <URL: https://docs.python.org/3/reference/datamodel.html?highlight=__g
   etattr__#the-standard-type-hierarchy>

So the only difference between a regular function and an instance method
object is the fact that the latter has a __self__ attribute set.

Although even that small difference can be paved over:

    def g():
        print("g")
    g.__self__ = a
    a.f = g


Marko



More information about the Python-list mailing list