Attaching functions to objects as methods

Steven Bethard steven.bethard at gmail.com
Fri Jul 7 22:30:07 EDT 2006


John Machin wrote:
> Injecting a "private" method into a particular instance is not much more 
> complicated:
> 
>  >>> def own(self, arg):
> ...    print "own"
> ...    self.ozz = arg
> ...
>  >>> p = K()
>  >>> import types
>  >>> p.metho = types.MethodType(own, p)
>  >>> p.metho("plugh")
> own
>  >>> p.ozz
> 'plugh'
>  >>> o = K()
>  >>> o.metho("xyzzy")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'K' object has no attribute 'metho'
>  >>>
> 
> and no __makeyoureyesbleed__ __doubleunderscoremessingabout__ required :-)

=)

But of course you have to import a module instead. I'm not a huge fan of 
the types module because it's generally unnecessary, and I'm not 
particularly afraid of double-underscores as I write a lot of __init__ 
methods. ;-)

To the OP: regardless of which solution you eventually go with, it's 
definitely worth understanding how descriptors_ work. New-style classes 
wouldn't work without them.

.. _descriptors: http://users.rcn.com/python/download/Descriptor.htm

STeVe



More information about the Python-list mailing list