我正在尝试从基类访问变量。这是父类:
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
),因为它与派生类的 self
中的 __init__
是同一对象。您可以而且应该在任何地方都使用 self.some_var
。 super
用于从基类访问内容,但实例变量(如名称所示)是实例的一部分,而不是该实例的类的一部分。
父类中不存在属性some_var。
当您在
__init__
期间设置它时,它是在您的 Child 类的实例中创建的。
我遇到了同样的错误,这是一个愚蠢的错误
class one:
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")