Reputation: 721
so I'm writing a program in PyQt5 and making use of the QObject class. Here's the basic program.
class Object(QObject):
def __init__(self, parent=None):
super(Object, self).__init__(parent)
self.field = []
class Object2(Object):
def __init__(self):
super(Object, self).__init__()
self.field.append(1)
if __name__ == '__main__':
o = Object2()
But I'm getting this error:
AttributeError: 'Object2' object has no attribute 'field'
I can't seem to find the cause of problem. Is it that a python child class cannot access it's parents attributes?
Upvotes: 2
Views: 2011
Reputation: 2470
The error you are getting is because of the arguments you are passing into super
. In Python 2 it takes 2 arguments: The first argument is the current class (Object2
), and the second argument is the current instance (self
).
The issue is you've passed the parent class instead of the current class.
So you want:
class Object2(Object):
def __init__(self):
super(Object2, self).__init__() # Current class: Object2
self.field.append(1)
In Python 3, it is no longer required to pass these arguments into super
. So you would just do:
class Object2(Object):
def __init__(self):
super().__init__()
self.field.append(1)
See also:
https://stackoverflow.com/a/5066411/7220776
Python 2 docs: https://docs.python.org/2/library/functions.html#super
Python 3 docs: https://docs.python.org/3/library/functions.html#super
Upvotes: 3