[英]Calling member methods from class object in python 3
我有這段代碼:
class ABC:
def test():
print('Hi there')
ABC.test()
哪個輸出:
Hi there
鑒於此失敗:
ABC().test()
TypeError: test() takes 0 positional arguments but 1 was given
# Makes sense
我們知道,當我們調用classmethod
像<classname>.<methodname>()
該類隱含作為參數傳遞給它,但test
這里不帶任何參數。
為什么由於意外的參數而看不到TypeError
? 該類不是通過傳遞給test
的參數嗎?
什么都不會傳遞給test()
因為在訪問類時函數不會綁定任何東西。 它保持未綁定狀態 ,您將獲得原始功能:
>>> class ABC:
... def test():
... print('Hi there')
...
>>> ABC.test
<function ABC.test at 0x1082706c0>
只要傳入正確數量的參數,就可以直接調用函數。 此處為0,因此ABC.test()
成功。
它不是classmethod
,它需要使用@classmethod
裝飾(或生成classmethod
對象並將其存儲為類的屬性),這時訪問屬性會將函數綁定到class對象,從而生成綁定method
:
>>> class ABC:
... @classmethod
... def test():
... print('Hi there')
...
>>> ABC.test
<bound method ABC.test of <class '__main__.ABC'>>
調用此方法將導致異常:
>>> ABC.test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes 0 positional arguments but 1 was given
也可以綁定函數,但只能在類的實例上訪問時。 function
對象和classmethod
對象都實現描述符協議 ,訪問類和實例上的屬性將觸發描述符的__get__
方法。 但是在這種情況下,只有classmethod
對象會返回綁定方法,而函數只會返回自身。
具體地, 描述符__get__
方法被傳遞None
為第一個參數,以結合,當屬性訪問是一類的對象,並且實例在實例時訪問。 classmethod().__get__()
忽略實例參數,並生成綁定到第二個參數( owner
)的方法對象。 當第一個參數為None
,函數將返回self
,否則將返回綁定到實例的方法對象:
>>> def foo(boundto='nothing'):
... print(f'Bound to {boundto}')
...
>>> foo.__get__('instance', 'owner')()
Bound to instance
>>> foo.__get__(None, 'owner')()
Bound to nothing
>>> classmethod(foo).__get__('instance', 'owner')()
Bound to owner
>>> classmethod(foo).__get__(None, 'owner')()
Bound to owner
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.