Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

13.1 Inheritance basics

Learning objectives

By the end of this section you should be able to

  • Identify is-a and has-a relationships between classes.
  • Differentiate between a subclass and a superclass.
  • Create a superclass, subclass, and instances of each.

is-a vs has-a relationships

Classes are related to each other. An is-a relationship exists between a subclass and a superclass. Ex: A daffodil is a plant. A Daffodil class inherits from a superclass, Plant.

Is-a relationships can be confused with has-a relationships. A has-a relationship exists between a class that contains another class. Ex: An employee has a company-issued laptop. Note: The laptop is not an employee.

Inheritance in Python

Inheritance uses an is-a relationship to inherit a class from a superclass. The subclass inherits all the superclass's attributes and methods, and extends the superclass's functionality.

In Python, a subclass is created by including the superclass name in parentheses at the top of the subclass's definition:


    class SuperClass:
        # SuperClass attributes and methods
    
    class SubClass(SuperClass):
        # SubClass attributes and methods