Python: 'super' object has no attribute 'attribute_name'
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(C开发者_运维知识库hild, 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?
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.
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
class one: def init(self): print("init") def status(self): print("This is from 1")
This was my parent class
class two:
def __init__(self):
print("init")
def status(self):
super().status()
print("This is from 2")
This was the child class
a = one()
a.status()
b = two()
b.status()
I was getting same error
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'
>
The problem was, I was not entering argument after declaring class two, "class two:" should be "class two(one)" so the solution was.
class two(one):
def __init__(self):
print("init")
def status(self):
super().status()
print("This is from 2")
精彩评论