Python: 'super' object has no attribute 'attribute_name'

浪子不回头ぞ 提交于 2019-12-03 15:57:50

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6075758/python-super-object-has-no-attribute-attribute-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!