Python:'super'对象没有属性'attribute_name'

时间:2011-05-20 17:48:16

标签: python attributes super

我正在尝试从基类访问变量。这是父类:

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中从基类访问变量的推荐方法是什么?

3 个答案:

答案 0 :(得分:20)

在基类的__init__运行之后,派生对象具有在那里设置的属性(例如some_var),因为它与派生类'{{中self的对象完全相同1}}。您可以而且应该只在任何地方使用__init__self.some_var用于从基类访问内容,但实例变量(如名称所示)是实例的一部分,而不是该实例类的一部分。

答案 1 :(得分:5)

Parent类中不存在some_var属性。

__init__期间设置时,它是在您的Child类的实例中创建的。

答案 2 :(得分:0)

我遇到了同样的错误,这是一个愚蠢的错误

第一类: def init(自我): 打印(“初始化”) 定义状态(自我): print("这是从 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")
相关问题