python bound unbound method

<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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值