[英]Compare attributes of parent and child class in Python
我有一個 Python class 像這樣:
class A:
__val1: float = 0.0
__val2: float
def __init__():
validate()
def validate() -> bool:
if not hasattr(self, __val2): # how is this supposed to be done?
raise NotImplementedError()
return self.__val1 >= self.val2
我的目標是將A
用作抽象 class ,其中子類被迫實現__val2
。
我創建了一個孩子 class B
:
class B(A):
__val2 = 1.0
def __init__():
super().__init__()
當我初始化 class B
的 object 時,會拋出此錯誤:
E AttributeError: 'B' object has no attribute '_A__val2'
我嘗試像這樣修改B
:
class B(A):
A.__val2 = 1.0
[...]
但這會引發相同的異常。
嘗試相同但使用super
:
class B(A):
super.__val2 = 1.0
[...]
但這會引發另一個錯誤:
E TypeError: can't set attributes of built-in/extension type 'super'
處理這種抽象的 Pythonic 方式是什么? 應該如何實現validate()
以便檢查__val2
?
當您對 class 屬性名稱使用雙前下划線時, python 會將它們轉換為_<classname>_<varname>
。 因此,在您的情況下, A.__val2
變為A._A__val2
並且B.__val2
變為B._B__val2
,這意味着它們不會共享相同的名稱。 請參閱 Thierry Lathuille 在您的問題的評論中分享的鏈接,這里是 python 文檔的鏈接: https://docs.python.org/3/tutorial.html/privateclasses.html/privateclasses.html
您可以通過不使用雙下划線來解決此問題,因此 go 用於_val2
或val2
之類的東西。
您的代碼中還有一些其他問題:您的所有 class 方法都需要self
作為第一個參數,您需要通過調用self.<method_name>
來訪問它們。 因此,要訪問validate
,您需要使用self.validate()
調用它。 此外, hasattr
的第二個參數必須是字符串。
這是一個更新的示例,應該可以解決您的問題:
class A:
_val1: float = 0.0
_val2: float
def __init__(self):
self.validate()
def validate(self) -> bool:
if not hasattr(self, '_val2'):
raise NotImplementedError()
return self._val1 >= self._val2
class B(A):
_val2 = 1.0
def __init__(self):
super().__init__()
print(B()._val2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.