Calling methods without objects?

Chris Angelico rosuav at gmail.com
Mon Sep 25 18:58:11 EDT 2017


On Tue, Sep 26, 2017 at 8:49 AM, Stefan Ram <ram at zedat.fu-berlin.de> 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?

>>> stuff = []
>>> add_stuff = stuff.append
>>> add_stuff("spam")
>>> add_stuff("eggs")
>>> add_stuff("sausage")
>>> add_stuff("spam")
>>> stuff
['spam', 'eggs', 'sausage', 'spam']

In a typical method call, "obj.meth(args)", the "obj.meth" part is
itself a valid expression, and it evaluates to a bound method object.
I suppose you could call that mechanism "method binding" if you like,
but mainly it's just attribute lookup.

ChrisA



More information about the Python-list mailing list