您的位置:首页 > 编程语言 > Python开发

python bound unbound method

2014-03-24 10:38 246 查看
<function __main__.dd> assign function to class make it a unbound method of that class

eg: CLASSA.method1 = func1

>>> def fooFighters( self ):
...     print "fooFighters"
...
>>> A.fooFighters = fooFighters
>>> a2 = A()
>>> a2.fooFighters
<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>
>>> a2.fooFighters()
fooFighters


Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):

but you can not add other class's method(unbound method) to a class

In [96]: A.a

Out[96]: <unbound method A.a>

In [97]: B.me = A.a

In [98]: B.me

Out[98]: <unbound method A.a> // you see!!! it is still A.a

// but we can make A.a func, then set this func to B

import types

t.update = types.MethodType(another_update)

the function type has a
special
__get__
method
which is called when you perform an attribute lookup on the class itself. Instead of you getting the function object, the
__get__
method
of that function object is called, and that returns a bound method object (which is what supplies the
self
argument).

In [185]: ddf = B.__dict__['ddf']

In [186]: ddf

Out[186]: <function __main__.dd>

In [187]: B.ddf

Out[187]: <unbound method B.dd>

http://codeplayer.iteye.com/blog/48144
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: