3 回答

TA貢獻1155條經驗 獲得超0個贊
在Python中,函數和綁定方法是有區(qū)別的。
>>> 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'
添加回答
舉報