python中添加方法,等等
时间:2006-07-09 来源:pipehappy
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 <__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>
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'
>>>
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>
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'
>>>
相关阅读 更多 +