[英]<Class> Object has no attribute <attribute_name>
[英]Python: 'super' object has no attribute 'attribute_name'
我正在嘗試從基類訪問變量。 這是父類:
class Parent(object):
def __init__(self, value):
self.some_var = value
這是子類:
class Child(Parent):
def __init__(self, value):
super(Child, self).__init__(value)
def doSomething(self):
parent_var = super(Child, self).some_var
現在,如果我嘗試運行此代碼:
obj = Child(123)
obj.doSomething()
我收到以下異常:
Traceback (most recent call last):
File "test.py", line 13, in <module>
obj.doSomething()
File "test.py", line 10, in doSomething
parent_var = super(Child, self).some_var
AttributeError: 'super' object has no attribute 'some_var'
我究竟做錯了什么? 從 Python 中的基類訪問變量的推薦方法是什么?
在基類的__init__
運行之后,派生對象在那里設置了屬性(例如some_var
),因為它與派生類__init__
的self
是完全相同的對象。 你可以而且應該在self.some_var
地方使用self.some_var
。 super
用於從基類訪問內容,但實例變量(顧名思義)是實例的一部分,而不是該實例類的一部分。
Parent 類中不存在屬性 some_var。
當您在__init__
期間設置它時,它是在您的 Child 類的實例中創建的。
我有同樣的錯誤,這是一個愚蠢的錯誤
第一類: def init (self): print("init") def status(self): print("This is from 1")
這是我的父類
class two:
def __init__(self):
print("init")
def status(self):
super().status()
print("This is from 2")
這是兒童班
a = one()
a.status()
b = two()
b.status()
我遇到了同樣的錯誤
init
This is from 1
init
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "<string>", line 12, in status
AttributeError: 'super' object has no attribute 'status'
>
問題是,我在聲明第二類之后沒有輸入參數,“第二類:”應該是“第二類(一)”,所以解決方案是。
class two(one):
def __init__(self):
print("init")
def status(self):
super().status()
print("This is from 2")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.