0

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.
Brad D
  • 67
  • 1
  • 5
  • `SpecificAttribute` needs to call `GeneralAttribute.__init__` from its own `__init__` to set those attributes; the first assignment to `item` is completely irrelevant. I suggest you find a proper tutorial, and note that `GeneralAttribute` should inherit from `object` if you're using Python 2.x. – jonrsharpe Oct 15 '15 at 10:53

1 Answers1

2

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)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895