This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Inheritance

Inheritance

face Josiah Wang

As discussed in the video, inheritance represents an is-a relation.

  • Mammal is a type of animal
  • Programming Course is a type of course.

Inheritance example

When you inherit from a class, you inherit features from the class and add new features to it. In other words, you add new functionality without modifying the existing code (adhering to the open-closed principle of Software Engineering). You also reuse existing code, obeying the Don’t Repeat Yourself (DRY) principle.

Subclasses and superclasses

If B inherits from A, then B is called the subclass and A is called the superclass. In our example:

  • Character is the superclass of Hero and Enemy.
  • Knight is a subclass of Hero

You can also informally call A the parent class and B the child class.

Everything is an object!

All classes in Python 3 are subclasses of the object class. Everything should output True in the code below.

class Person:
    pass

p = Person()
print(issubclass(Person, object))
print(isinstance(p, object))

print(issubclass(int, object))
print(isinstance(3, object))