3 回答
![?](http://img1.sycdn.imooc.com/5f33c0c90001f9ad05720572-100-100.jpg)
TA贡献1155条经验 获得超0个赞
在Python中,函数和绑定方法是有区别的。
>>> def foo():
... print "foo"
...
>>> class A:
... def bar( self ):
... print "bar"
...
>>> a = A()
>>> foo
<function foo at 0x00A98D70>
>>> a.bar
<bound method A.bar of <__main__.A instance at 0x00A9BC88>>
>>>
绑定方法已被“绑定”(如何描述性)到实例,每当调用该方法时,该实例将作为第一个参数传递。
不过,作为类的属性(相对于实例)的可调用对象仍未绑定,因此您可以随时修改类定义:
>>> 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
以前定义的实例也会被更新(只要它们没有重写属性本身):
>>> a.fooFighters()
fooFighters
当您想要将方法附加到单个实例时,问题就出现了:
>>> def barFighters( self ):
... print "barFighters"
...
>>> a.barFighters = barFighters
>>> a.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: barFighters() takes exactly 1 argument (0 given)
当函数直接附加到实例时,它不会自动绑定:
>>> a.barFighters
<function barFighters at 0x00A98EF0>
>>> import types>>> a.barFighters = types.MethodType( barFighters, a ) >>> a.barFighters<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88 >>>>> a.barFighters()barFighters
>>> a2.barFighters()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: A instance has no attribute 'barFighters'
添加回答
举报