Introduction to Python ProgrammingXYZ Homework Edition

⇩ 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

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.