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

37 投票
3 回答
63818 浏览
提问于 2025-04-16 18:02

我想从父类中访问一个变量。这里是父类的代码:

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

我也遇到了同样的错误,真是个小失误。

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:" 应该改成 "class two(one)",所以解决办法就是这样。

class two(one):
def __init__(self):
    print("init")
def status(self):
    super().status()
    print("This is from 2")
7

属性 some_var 在父类里是不存在的。

当你在 __init__ 方法里设置它的时候,它其实是在你子类的实例中创建的。

46

在基类的 __init__ 方法运行之后,派生类的对象就会有在那里面设置的属性(比如 some_var),因为这个对象和派生类的 __init__ 方法里的 self 是同一个东西。你可以并且应该在任何地方使用 self.some_varsuper 是用来访问基类中的内容的,但实例变量(就像名字所说的)是属于某个实例的,而不是属于那个实例的类。

撰写回答