Python:“超级”对象没有属性“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 中从基类访问变量的推荐方法是什么?
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
And here's the child class:
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()
I get the following exception:
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'
What am I doing wrong? What is the recommended way to access variables from the base class in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基类的
__init__
运行后,派生对象具有在那里设置的属性(例如some_var
),因为它与中的self
是同一对象。派生类'__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 theself
in the derived class'__init__
. You can and should just useself.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.属性 some_var 在父类中不存在。
当您在 __init__ 期间设置它时,它是在您的 Child 类的实例中创建的。
The attribute some_var does not exist in the Parent class.
When you set it during
__init__
, it was created in the instance of your Child class.我得到了同样的错误,这是一个愚蠢的错误
这是我的父类
子类
这是我得到同样错误的
问题是,我在声明第二类后没有输入参数,
“二类:”应为“二类(一)”
所以解决方案是。
I got same error, and it was a silly mistake
This was my parent class
This was the child class
I was getting same error
The problem was, I was not entering argument after declaring class two,
"class two:" should be "class two(one)"
so the solution was.