Python: object 'super' does not have attribute 'attribute_name'

I am trying to access a variable from a base class. Here's the parent class:

class Parent(object): def __init__(self, value): self.some_var = value 

And here is 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 a base class in Python?

+7
source share
2 answers

After starting the __init__ base class, the derived object has the attributes set there (for example, some_var ), since it is the same object as self in the __init__ derived class. You can and should just use self.some_var everywhere. super designed to access materials from base classes, but instance variables (as indicated in the name) are part of the instance, not part of this instance class.

+17
source

The some_var attribute does not exist in the parent class.

When you set it during __init__ , it was created in an instance of your Child class.

+4
source

All Articles