Inheritance and super()
Inheritance lets one class build on another. The new class (the subclass) gets all the attributes and methods of the original (the parent, or base class) for free, and can add or change behaviour.
You name the parent in parentheses after the subclass name:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
rex = Dog("Rex")
print(rex.name) # Rex (inherited __init__)
print(rex.speak()) # Woof (overridden method)Dog did not define __init__, so it reused the one from Animal. It did define speak, which overrides the parent version.
Calling the parent with super()
Sometimes you want to extend the parent rather than fully replace it. super() gives you the parent so you can call its version, then add more. This is common in __init__:
class Cat(Animal):
def __init__(self, name, indoor):
super().__init__(name) # let Animal set self.name
self.indoor = indoor # then add our own
c = Cat("Milo", True)
print(c.name, c.indoor) # Milo TrueYou can check the family relationship with isinstance: a Cat is also an Animal.
print(isinstance(c, Animal)) # TrueStart from a parent class Shape with a method area(self) that returns 0. Define a subclass Square whose __init__ takes side, calls super().__init__(), stores self.side, and overrides area to return side * side. Create sq = Square(4).
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.