Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo

Learning objectives

By the end of this section you should be able to

  • Write overridden methods to change behavior of inherited methods.
  • Use super() to access superclass methods.
  • Identify applications of polymorphism in method and function use.

Overriding methods

Sometimes a programmer wants to change the functions a subclass inherits. Mint is a subclass that has the same functionality as Plant, except for one function. A subclass can override a superclass method by defining a method with the same name as the superclass method.

Checkpoint

Overriding a superclass method

Concepts in Practice

Overriding methods

1.
Suppose a programmer inherits the ContractTax class from class Tax and wants to override Tax's calc_tax(). What should the programmer do?
  1. Define another calc_tax() method in Tax.
  2. Define a calc_tax() method in ContractTax.
  3. Define a function that takes a ContractTax instance.
2.
Which is the error in the program that attempts to override calc_tax() for ContractTaxDE?
class Tax:
  def calc_tax(self):
    print('Calculating tax')

class ContractTax(Tax):
  def calc_tax(self):
    print('Calculating contract tax')

class ContractTaxDE(ContractTax):
  def calc_tax():
    print('Calculating German contract tax')

my_tax = ContractTaxDE()
my_tax.calc_tax()
  1. ContractTaxDE must inherit from Tax, not ContractTax.
  2. ContractTaxDE's definition of calc_tax() is missing a parameter.
  3. ContractTaxDE can't override calc_tax() since ContractTax already has.
3.
The following program doesn't override calc_tax(). Why?
class Tax:
  def calc_tax(self):
    print('Calculating tax')
    total = 0 # To replace with calculation
    return total

class ContractTax:
  def calc_tax(self):
    print('Calculating contract tax')
    total = 0 # To replace with calculation
    return total

my_tax = ContractTax()
my_tax.calc_tax()
  1. An overridden method cannot return a value.
  2. Tax doesn't specify calc_tax() can be overridden.
  3. ContractTax isn't inherited from Tax.

super()

super() is a special method that provides a temporary superclass object instance for a subclass to use. super() is commonly used to call superclass methods from a subclass. super() is commonly used in a subclass's __init__() to assign inherited instance attributes. Ex: super().__init__().

Checkpoint

Using super() to call the superclass __init__() method

Concepts in Practice

Using super()

Consider the following program.

1
class Polygon:
2
  def __init__(self, num_sides=3):
3
    self.num_sides = num_sides
4
5
class Rectangle(Polygon):
6
  def __init__(self, ln=1, wd=1):
7
    super().__init__(4)
8
    self.length = ln
9
    self.width = wd
10
11
class Square(Rectangle):
12
  def __init__(self, side=1):
13
    super().__init__(side, side)
14
    self.side = side
15
16
sq_1 = Square(5)
17
print(sq_1.num_sides)
4.
Line 16 executes and Square's __init__() is called on line 12. Line 13 executes and the superclass's __init__() is called. Which line does control flow move to next?
  1. 2
  2. 6
  3. 14
5.
The next line executes. Which line does control flow move to next?
  1. 2
  2. 6
  3. 14
6.
The method call returns. Lines 8 and 9 execute to initialize length and width, and Rectangle's __init__() returns. Which line does control flow move to next?
  1. 12
  2. 14
  3. 17
7.
Square's __init__() returns and control flow moves to line 17. What is the output?
  1. 3
  2. 4
  3. 5

Polymorphism

Polymorphism is the concept of having many forms. In programming, a single name can be used for multiple functionalities. Within inheritance, polymorphism is the basis of method overriding, as multiple methods have the same name.

Example 13.1

Polymorphism and inheritance

The name display() maps to multiple methods. The class type of the calling object determines which display() method is executed.

    class Plant:
      def display(self):
        print("I'm a plant")

    class Mint(Plant):
      def display(self):
        print("I'm a mint")

    class Lavender(Mint):
      def display(self):
        print("I'm a lavender")

    mint_1 = Mint()
    mint_1.display()

    lavender_1 = Lavender()
    lavender_1.display()

The code's output is:

    I'm a mint
    I'm a lavender

Polymorphism can also be used with methods of unrelated classes. The class type of the calling object determines the method executed.

Example 13.2

Polymorphism and methods

Tax and ContractTax are unrelated classes that each define calc_tax(). calc_tax() isn't overridden as ContractTax isn't inherited from Tax.

    class Tax:
      def __init__(self, value):
        self.value = value
  
      def calc_tax(self):
        print("Calculating tax")
        total = 0.10 * self.value  # To replace with calculation
        return total
  
    class ContractTax:
      def __init__(self, value):
        self.value = value
  
      def calc_tax(self):
          print("Calculating contracts tax")
          total = 0.15 * self.value  # To replace with calculation
          return total
  
    my_tax = ContractTax(value=1000)  # Replace 1000 with any value
    result = my_tax.calc_tax()
    print(f"Total tax: ${result}")

The code's output is:

    Calculating contracts tax
    Total tax: $150.00

Polymorphism allows methods to be called with different parameter types. Many built-in operators and functions have this utility.

Example 13.3

Polymorphism and functions

len() can be called with multiple types, including lists and strings.

    tree_list = ["ash", "hazel", "oak", "yew"]
    tree_1 = tree_list[0]
    print(len(tree_list))
    print(len(tree_1))

The code's output is:

    4
    3

Concepts in Practice

Polymorphism in practice

8.
Consider the example. What is the output?
class Polygon:
  def print_type(self):
    print("Polygon type")

class Rectangle(Polygon):
  def print_type(self):
    print("Rectangle type")

class Square(Rectangle):
  def print_type(self):
    print("Square type")

sq_1 = Square()
sq_1.print_type()
  1. Polygon type
  2. Rectangle type
  3. Square type
9.
Which is an example of polymorphism for the multiplication operator?
  1. x = 3 * 4
    y = 3 * "la"
    
  2. x = 3 * 4
    y = str(x)
    
  3. x = 3 * 4
    y = x * x
    

Try It

Overriding methods

Given the Pet class, create a Bird class inherited from Pet and a Finch class inherited from Bird. Override the display() method in Bird and Finch such that the program output is:

    Pet type: Bird
    Bird type: Finch

Try It

Using super()

Given the Employee class, create a Developer class inherited from Employee with methods __init__() and print_info() such that:

__init__()

  • Uses super() to call Employee's __init__() to initialize e_id and hire_year.
  • Assigns lang_xp with list parameter lang_xp.

print_info()

  • Uses super() to print e_id and hire_year.
  • Prints "Language(s):" followed by lang_xp.
Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.