Skip to content
dreamcode
dreamcode
Map
Inheritance
Lesson 45 of 77
+15 XP on finish
OBJECTSChapter 8 · Objects and Classes

Inheritance

A class can inherit from another: class Comet(SpaceObject): gets every method of SpaceObject for free. Override a method by defining it again in the child, and call the parent's version with super(). isinstance(obj, SomeClass) checks the type, and it counts parent classes too.

Worked example

How it reads

  • Comet(SpaceObject) means a Comet is a SpaceObject
  • super().__init__(name) runs the parent setup before adding more
  • Overriding describe replaces it, and super().describe() still reaches the original
Cloud tip: Use inheritance for a true "is a" relationship. When one object merely uses another, keep it as an attribute instead.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Add a Dog class that inherits from Animal and overrides speak to return Rex says woof for a dog named Rex. Print Dog("Rex").speak().

Press Run to check your work.