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.
Concepts in Practice
Overriding methods
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__().
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) |
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
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 callEmployee's__init__()to initializee_idandhire_year. - Assigns
lang_xpwith list parameterlang_xp.
print_info()
- Uses
super()to printe_idandhire_year. - Prints
"Language(s):"followed bylang_xp.