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.
1
  • 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. Commented Oct 15, 2015 at 10:53

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Your example doesn't behave in a very intuitive way - item.Attribute4 == 1 and item.Attribute1 == 5.
Argh, yes sorry. Editing.
Probably better to avoid the args stuff anyway as it can be confusing for beginners (and, apparently, to people who have been doing Python for ten years...)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.