I just started learning Python, and I am afraid that I am not understanding the proper use of Class and Inheritance. In the following code, I am trying to create a class that defines general attributes for an item. I would then like to add more attributes, using another class, while retaining the previously defined attributes of the item.
class GeneralAttribute :
def __init__(self, attribute1, attribute2, attribute3) :
self.Attribute1 = attribute1
self.Attribute2 = attribute2
self.Attribute3 = attribute3
class SpecificAttribute(GeneralAttribute) :
def __init__(self, attribute4, attribute5, attribute6, attribute7) :
self.Attribute4 = attribute4
self.Attribute5 = attribute5
self.Attribute6 = attribute6
self.Attribute7 = attribute7
item = GeneralAttribute(7, 6, 5)
item = SpecificAttribute(1, 2, 3, 4)
print item.Attribute1
# This leads to an error since Attribute1 is no longer defined by item.
1 Answer 1
That's not how inheritance works. You don't instantiate them separately; the point is that you only instantiate SpecificAttribute, and it is already also a GeneralAttribute because inheritance is an "is-a" relationship.
In order to enable this, you need to call the GeneralAttribute __init__ method from within the SpecificAttribute one, which you do with super.
class SpecificAttribute(GeneralAttribute) :
def __init__(self, attribute1, attribute2, attribute3, attribute4, attribute5, attribute6, attribute7):
super(SpecifcAttribute, self).__init__(attribute1, attribute2, attribute3)
self.Attribute4 = attribute4
self.Attribute5 = attribute5
self.Attribute6 = attribute6
self.Attribute7 = attribute7
item = SpecificAttribute(1, 2, 3, 4, 5, 6, 7)
3 Comments
item.Attribute4 == 1 and item.Attribute1 == 5.
SpecificAttributeneeds to callGeneralAttribute.__init__from its own__init__to set those attributes; the first assignment toitemis completely irrelevant. I suggest you find a proper tutorial, and note thatGeneralAttributeshould inherit fromobjectif you're using Python 2.x.