6. Inheritance

Inheritance lets a class reuse the attributes and methods of another class. Write the parent class in parentheses:

  • Animal is the parent (or base) class.
  • Dog is the child (or subclass). It inherits every method of Animal.
  • Dog can add its own methods and attributes.
  • A Dog is also an Animal, so isinstance(dog, Animal) is True.

When the parent has an __init__, the child usually defines its own and calls the parent's initializer with super():

  • super() refers to the parent class; super().__init__(name) runs the parent initializer.
  • Without that call, self.name would never be set.

A child can override a method by defining one with the same name. Its version replaces the parent's for that child:

super() also works inside an override: super().speak() runs the parent's version first.

Coming from JavaScript? class Dog extends Animal declares inheritance the same way, and super(...) calls the parent constructor. Python writes class Dog(Animal): and super().__init__(...).

#01

Inherit a method

Define Animal with a method speak(self) that prints .... Define Dog that inherits from Animal and has an empty body with pass. Create one dog with Dog() and call speak().

The method is not written in Dog; it comes from Animal.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Call the parent initializer

Define Animal with __init__(self, name) that stores self.name. Define Dog that inherits from Animal and has its own __init__(self, name) that calls the parent initializer with super(), so the inherited name attribute is set.

Create dog = Dog("Rex") and print dog.name.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Override a method

Define Animal with speak(self) that prints .... Define Dog that inherits from Animal and defines its own speak(self) that prints Woof.

Create one Animal() and one Dog(), then call speak() on each, in that order. The dog uses its own version; the animal keeps the original.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Add a method in the child

Define Animal with __init__(self, name) that stores self.name. Define Dog that inherits from Animal without overriding __init__, and add a method fetch(self) that prints <name> fetches the ball, using the inherited self.name.

Create Dog("Rex") and call fetch() on it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

A child is also the parent type

Define Animal with __init__(self, name) that stores self.name. Define Dog that inherits from Animal with an empty body. Create dog = Dog("Rex").

Print isinstance(dog, Dog), then isinstance(dog, Animal). An instance of a child class also belongs to its parent class.

Print exactly:

Create a free account to save your progress and unlock chapter 2.