python中添加方法,等等
Functions are descriptors, 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
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)
>
>>> fun.__get__(x, test)
>
>>> fun.__get__(None, test)
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 "", line 1, in ?
AttributeError: 'K' object has no attribute 'metho'
>>>