Calling methods without objects?

Thomas Jollans tjol at tjol.eu
Mon Sep 25 19:04:50 EDT 2017


On 26/09/17 00:49, Stefan Ram wrote:
> |>>> from random import randint
> |
> |>>> randint
> |<bound method Random.randint of <random.Random object at 0x0000000000389798>>
> |
> |>>> randint.__self__
> |<random.Random object at 0x0000000000389798>
> |
> |>>> randint( 2, 3 )
> |2
>
>   It seems I am calling the method »randint« of the object at
>   »0x389798«, but I do not have to write the object into the
>   call!?
>
>   So, is there some mechanism in Python that can bind a method
>   to an object so that the caller does not have to specify the
>   object in the call?
>
>   If so, how is this mechanism called?

Yes, that's how all methods work in Python. When an object is
constructed from a class, all functions in the class are turned into
method objects that refer back to the original object.

In [1]: class C:

   ...: def m(self):

   ...: return True

   ...:

In [2]: C.m

Out[2]: <function __main__.C.m>

In [3]: C().m

Out[3]: <bound method C.m of <__main__.C object at 0x7f5b2813f1d0>>

In [4]: m = C().m

In [5]: m

Out[5]: <bound method C.m of <__main__.C object at 0x7f5b2813fef0>>

In [6]: m()

Out[6]: True

In [7]: m.__self__

Out[7]: <__main__.C at 0x7f5b2813fef0>

In [8]: m.__func__

Out[8]: <function __main__.C.m>

In [9]: m.__func__ is C.m

Out[9]: True




More information about the Python-list mailing list