Re: Calling methods without objects?
Op 2017-09-25, Stefan Ram schreef: > 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? > Others have already explained the details how functions become bound methods, but I would just point out that it is an instance of a piece of very general functionality: the descriptor protocol. https://docs.python.org/3.6/howto/descriptor.html With this, you can create your own objects which do some arbitrary special thing when accesses on an instance. Stephan -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling methods without objects?
Thomas Jollans wrote: 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. That's not quite true. Nothing is done to the methods at the time an instance is created; rather, a bound method object is created each time a method is looked up via an instance. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling methods without objects?
On 26/09/17 01:04, Thomas Jollans wrote: > > In [1]: class C: > >...: def m(self): > >...: return True I'll have to give my MUA a stern talking to about the importance of whitespace. Anyway, you know what I mean. > >...: -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling methods without objects?
On Tue, Sep 26, 2017 at 8:49 AM, Stefan Ramwrote: > |>>> from random import randint > | > |>>> randint > |> > | > |>>> randint.__self__ > | > | > |>>> 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 -- https://mail.python.org/mailman/listinfo/python-list