所以,我一直在嘗試實作以下內容:
from abc import ABC
from abc import abstractmethod
class parent(ABC):
@property
@abstractmethod
def example_variable(self)->str:
...
@abstractmethod
def example_method(self)->int:
...
def __init__(self, foo: int):
self.foo = foo
class child(parent):
def example_method(self)->int:
return self.foo 10
example_variable = f"This is example variable of value {self.example_method()}"
if __name__ == "__main__":
example_object = child(59)
print(example_object.example_variable)
如您所見,我創建了一個具有抽象屬性和方法的抽象類,并嘗試通過使用實體變數的值來計算簡單值并使用該值來設定子類的值使用 F 字串的屬性。
但困難在于,由于某種原因,解釋器無法識別 的自我參考example_method():
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [7], line 17
14 def __init__(self, foo: int):
15 self.foo = foo
---> 17 class child(parent):
18 def example_method(self)->int:
19 return self.foo 10
Cell In [7], line 21, in child()
18 def example_method(self)->int:
19 return self.foo 10
---> 21 example_variable = f"This is example variable of value {self.example_method()}"
NameError: name 'self' is not defined
我一直試圖弄清楚這一點,但沒有成功。
我嘗試洗掉self參考:
example_variable = f"This is example variable of value {example_method()}"
但隨后它拋出錯誤:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [10], line 17
14 def __init__(self, foo: int):
15 self.foo = foo
---> 17 class child(parent):
18 def example_variable(self)->int:
19 return self.foo 10
Cell In [10], line 21, in child()
18 def example_variable(self)->int:
19 return self.foo 10
---> 21 example_variable = f"This is example variable of value {example_method()}"
NameError: name 'example_method' is not defined
我的問題是,為什么 python 解釋器不能正確評估自參考?該方法尚未實體化嗎?如果是這樣,那么實體化的正確方法是example_method()什么?
uj5u.com熱心網友回復:
'self' 引數僅在類方法中被識別,因為它作為引數傳遞給方法。(默認情況下,Python 類方法的第一個引數是指向該類的指標)上述情況下的 example_variable 是在方法外部定義的,因此使用 self.example_method() 將不正確。
其次,如果您在子類中繼承父類,則必須首先使用 super().__init__() 對其進行初始化,以便識別其方法。
我的建議是在子類的建構式中或通過其他方法在本地定義 example_variable。
uj5u.com熱心網友回復:
我想說你的問題在于你想要的是 example_variable 是在 init 期間定義的變數,所以在__init__. 但是,這樣做我不確定 example_variable 在初始化期間是否會被 example_method 的值固定;如果您希望 example_variable 在 example_method 的結果發生變化的情況下發生變化,那么 example_variable 可能應該保留一個 @property 函式,就像您在父類中定義它的方式一樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/528249.html
