Attaching functions to objects as methods

Steven Bethard steven.bethard at gmail.com
Fri Jul 7 19:55:11 EDT 2006


tac-tics wrote:
> Python is a crazy language when it comes to object versatility. I know
> I can do:
> 
>>>> class test:
> ...    def __init__(self):
> ...         pass
>>>> x = test()
>>>> def fun():
> ...     print "fun"
>>>> x.fun = fun
>>>> x.fun()
> fun
> 
> However, experimenting shows that these attached functions are not
> bound to the object. They do not accept the 'self' parameter. I want to
> know how one goes about doing that. How do I bind a function to an
> object to act as if it were a method?

Functions are descriptors[1], and their __get__ method is used to bind 
them to a particular instance::

     >>> class test(object):
     ...     def __init__(self):
     ...         pass
     ...
     >>> x = test()
     >>> def fun(self):
     ...     print "fun", self
     ...
     >>> x.fun = fun.__get__(x, test)
     >>> x.fun()
     fun <__main__.test object at 0x00E6D730>

Note that calling __get__ returns a bound method, and that method can be 
bound to an instance or a class depending on the parameters of __get__::

     >>> fun.__get__(x, None)
     <bound method ?.fun of <__main__.test object at 0x00E74510>>
     >>> fun.__get__(x, test)
     <bound method test.fun of <__main__.test object at 0x00E74510>>
     >>> fun.__get__(None, test)
     <unbound method test.fun>



[1] http://users.rcn.com/python/download/Descriptor.htm

STeVe



More information about the Python-list mailing list