簡體   English   中英

從python 3中的類對象調用成員方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM