測試環境為 CentOS 8 x86_64 (虛擬機)
參考文章 – https://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static
下面來看一下什麼是 bound & unbound method 與他們的差異.
[root@localhost ~]# python3 Python 3.6.8 (default, Mar 25 2022, 11:15:52) [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux Type "help", "copyright", "credits" or "license" for more information.
Class 內定義了 bound (method_one) & unbound (method_two) method
class Test: def method_one(self): print ("Called method_one") def method_two(): print ("Called method_two")
在定義好的 class 其 method 皆為 function.
>>> type(Test.method_one) <class 'function'> >>> type(Test.method_two) <class 'function'>
- Bound Method
我們無法直接透過 class 來使用 method_one 這個 method.>>> Test.method_one() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: method_one() missing 1 required positional argument: 'self'
method_one 需傳入 self 參數,我們須先產生 instance 後才能使用它.
>>> a_test = Test()
透過 instance.method 或是 class.method(instance) 的方式來使用.
>>> a_test.method_one() Called method_one >>> Test.method_one(a_test) Called method_one
a_test.method_one 與 a_test.method_two 皆為 Bound method ,但 a_test.method_two 無法透過這個方式來使用.
>>> a_test.method_one <bound method Test.method_one of <__main__.Test object at 0x7f1c77c15eb8>> >>> a_test.method_two <bound method Test.method_two of <__main__.Test object at 0x7f1c77c15eb8>>
- Unbound Method
在定義好的 class 其 method 沒有傳入 self 參數的 method 稱為 Unbound method , 要怎麼使用 unbound (method_two) method ,直接透過 class.method 即可使用.>>> Test.method_two() Called method_two
無法透過 instance 來使用.
>>> a_test.method_two() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: method_two() takes 0 positional arguments but 1 was given
- @staticmethod
需使用 @staticmethod 才能讓 method_two 透過 instance 來使用.class Test: def method_one(self): print ("Called method_one") @staticmethod def method_two(): print ("Called method_two")
>>> a_test = Test() >>> a_test.method_one() Called method_one >>> a_test.method_two() Called method_two
a_test.method_two 型別為 function.
>>> a_test.method_one <bound method Test.method_one of <__main__.Test object at 0x7f1c77b9f240>> >>> type(a_test.method_one) <class 'method'>
>>> a_test.method_two <function Test.method_two at 0x7f1c77bfeb70> >>> type(a_test.method_two) <class 'function'>
沒有解決問題,試試搜尋本站其他內容