Lessons · Python · inheritance and super()
A subclass gets the parent's methods and can change some
class Puppy(Dog) makes Puppy a kind of Dog: every Dog method works on a Puppy, and Puppy can add or override methods. super() reaches the parent's version.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
A frame of code that is almost the same for several kinds of thing: a savings account is an account with interest, an admin is a user with extra powers. Inheritance keeps the shared part in one place.
How to think about it
Ask: is this a KIND OF that? If a Puppy is a Dog, inherit. If it merely uses a Dog, store one as an attribute instead. In the child's __init__, call super().__init__(...) first so the parent's attributes exist.
Worked example
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + ' says Woof'
class Puppy(Dog):A Puppy is a Dog.
def __init__(self, name):
super().__init__(name)Let Dog set up name first.
self.age = 0Then add what only a Puppy has.
def speak(self):Override: the child's version wins.
return self.name + ' says Yip'
print(Puppy('Bo').speak(), isinstance(Puppy('Bo'), Dog))Bo says Yip TrueYour turn
Let the parent set up the shared attributes first.
class Admin(User):
def __init__(self, name):
.__init__(name)
self.powers = ['ban']Solve one with the tests running
The trap
Writing a child __init__ without calling super().__init__. The parent's attributes are never set, and the first self.name read raises AttributeError from somewhere far from the cause.