Inheritance & super()

Classes & Objects, lesson 4 of 6

🏗️ Classes & Objects, lesson 4 of 6

Inheritance & super()

Build specialized classes on top of existing ones.

10 min

1 exercise

1 quiz

0/2 solved

Getting Python ready… examples can run in a moment.

Inheritance lets one class reuse and extend another. class Dog(Animal): makes Dog a subclass (child) of Animal (the parent).

The child automatically gets all of the parent's methods. It can override some of them and add new ones.

Example

Override a method

introduce is written once, yet calls the right speak for each object. That's called polymorphism. Add a Cow subclass that says "Moo".

super() gives you the parent's version of a method. You'll use it most in __init__: let the parent set up the shared attributes, then add the extras.

Example

Extending with super()

Manager reuses the parent's setup and formula and only adds what's different. Add a third team member and re-run.

Quiz

What does this print?

"Is-a" checks. isinstance(obj, Parent) is also True for subclasses: a Dog is an Animal. You already used inheritance in class MyError(Exception).

Use inheritance for real is-a relationships. For has-a (a Car has an Engine), store one object as an attribute of the other instead.

Example

isinstance and issubclass

The last line explains why except Exception also catches a ValueError.

Exercise

A family of shapes

Shape is done. Write two subclasses:

  • Rectangle(width, height): calls super().__init__("Rectangle"), stores the sizes and overrides area()
  • Circle(radius): calls super().__init__("Circle"), stores the radius and overrides area() (π × r²)

Don't write describe() again: it's inherited.