我讀過,可以在Python中向現有對象(即不在類定義中)添加方法。我了解這樣做并不總是一件好事。但是怎么可能呢?
4 回答

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
在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>
要綁定它,我們可以在類型模塊中使用MethodType函數:
>>> 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'
通過閱讀有關描述符和元類 編程的信息,可以找到更多信息。
添加回答
舉報
0/150
提交
取消