2

I have the following code:

class aa(object):
    def __init__(self):
        self.height = 12

class bb(aa):
    def __init__(self):
        self.weight = 13

AA = aa()
BB = bb()

I am trying to access the variable initialized in the Parent class (aa), using the Child object as below. Please suggest the correct way to do it as I am getting errors doing this way:

(If someone can point me to a good documentation on subclassing in Python, it would be great.)

print AA.height # 12
print BB.height # Error
1

2 Answers 2

3

You must call __init__ from the superclass. It will not be called implicitly.

class bb(aa):
    def __init__(self):
        super(bb, self).__init__()
        self.weight = 13
Sign up to request clarification or add additional context in comments.

Comments

2

You need to explicitly initialize the superclass. Edit your __init__ method of bb such that it looks like this:

class bb(aa):
    def __init__(self):
        super(bb, self).__init__()  # Call the __init__ method of the superclass.
        self.weight = 13

It should then work:

print AA.height  # 12
print BB.height  # 12

As for the documentation on using superclasses, refer to the super function in the documentation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.