Python:“超级"对象没有属性"attribute_name" [英] Python: 'super' object has no attribute 'attribute_name'
问题描述
我正在尝试从基类访问变量.这是父类:
I am trying to access a variable from the base class. Here's the parent class:
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
现在,如果我尝试运行以下代码:
Now, if I try to run this code:
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中从基类访问变量的推荐方法是什么?
What am I doing wrong? What is the recommended way to access variables from the base class in Python?
推荐答案
在运行基类的__init__
之后,派生对象在此处设置了属性(例如some_var
),因为它是与__init__
中.您可以并且应该在任何地方都使用self.some_var
. super
用于访问基类中的内容,但是实例变量(如名称所示)是实例的一部分,而不是该实例的类的一部分.
After the base class's __init__
ran, the derived object has the attributes set there (e.g. some_var
) as it's the very same object as the self
in the derived class' __init__
. You can and should just use self.some_var
everywhere. super
is for accessing stuff from base classes, but instance variables are (as the name says) part of an instance, not part of that instance's class.
这篇关于Python:“超级"对象没有属性"attribute_name"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!