我想實作這種情況 - 我有一個類,我有一些包含外部方法的變數,在某些情況下可以重新定義方法。它可能看起來像:
def my_print(self):
print('my print is called')
class example():
some_method = my_print
def __init__(self):
self.some_method()
def test(self):
self.some_method()
所以,它有效:
a = example()
a.test()
結果如下所示:
my print is called (from init)
my print is called (from test)
但如果重新定義some_method:
a = example()
a.some_method = my_print
a.test()
它回傳一個錯誤,表示我需要self在該行中作為引數給出self.some_method():
TypeError: my_print() missing 1 required positional argument: 'self'
為什么會發生這種情況,也許有人知道解決這個問題的訣竅?
uj5u.com熱心網友回復:
這是.Python 中的一個微妙之處。它既在類上查找方法,又將方法系結到實體。這個系結隱含地提供了類實體作為第一個引數,self. 看這個:
>>> print(example.some_method)
<function my_print at 0x7f66c4129f30>
>>> print(a.some_method)
<bound method my_print of <test.example object at 0x7f66c41c2290>>
但是,當在類上但在實體上找不到方法時,系結不會發生:
>>> a = example()
my print is called
>>> a.some_method = my_print
>>> print(a.some_method)
<function my_print at 0x7f66c4129f30>
這在Python 參考中有所說明:
同樣重要的是要注意,作為類實體屬性的用戶定義函式不會轉換為系結方法;這只發生在函式是類的屬性時。
因此,解決方案是確保該方法始終是類實體的屬性,并相應地呼叫它:
class example():
def __init__(self):
self.some_method = my_print
self.some_method(self)
def test(self):
self.some_method(self)
看起來很奇怪,效果很好。
如果您希望方法始終是類的屬性,請考慮使用繼承。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434648.html
標籤:python-3.x 班级 自己
上一篇:如何使用CSS覆寫類樣式?
