Attaching functions to objects as methods

John Machin sjmachin at lexicon.net
Fri Jul 7 20:30:48 EDT 2006


On 8/07/2006 9:29 AM, 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? It looks like the classmethod()
> built-in looks *similar* to what I want to do, but not quite.
> 
> Any help would be awesome =-)
> 

Call me crazy, but wasn't this discussed in a thread only a few days ago?

Injecting a method into a class, so that even already-created instances 
have that method, is trivial:

 >>> class K(object):
...     pass
...
 >>> def fun(self, arg):
...     print "fun"
...     self.frob = arg
...
 >>> o = K()
 >>> K.methc = fun
 >>> o.methc("xyz")
fun
 >>> o.frob
'xyz'
 >>>

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 :-)

Cheers,
John



More information about the Python-list mailing list