Inheritance reuses code

Case Study: Building Software in Python

Mark Pedigo

Principal Data Scientist

Roadmap

Roadmap showcasing what parts of the project we've finished and which we'll be starting.

Case Study: Building Software in Python

Review of what you've built so far

  • BasicCalculator()
    • Basic arithmetic operations
  • FinancialCalculator
    • Inherits from BasicCalculator
    • Method for financial calculation
class BasicCalculator:
  def multiply(self, x, y):
      result = x * y
      return result
  ...
# Child of BasicCalculator
class FinancialCalculator(BasicCalculator):
    def monthly_interest(self, annual_interest_rate):
        return self.divide(annual_interest_rate, 12)
    ...
Case Study: Building Software in Python

Inheritance Reuses Code

  • Inheritance for code reuse
    • Reuse code from a parent class
  • Class hierarchy
    • Inherit from child to "grandchild" classes
  • Flexible structure
    • Develop a flexible and organized class hierarchy
Case Study: Building Software in Python

Other types of inheritance

  • Multilevel inheritance
    • Class inherits from a subclass of another class
    • Used in case study - BasicCalculator to FinancialCalculator to MortgageCalculator
  • Hierarchical inheritance
    • Multiple classes inherit from the same parent class
  • Multiple inheritance
    • Class inherits from two or more unrelated classes
Case Study: Building Software in Python

Using super()

  • Access parent methods and properties
    • Use super() without directly naming the parent class
  • Handles complex inheritance
    • Prevents code duplication and errors in class hierarchies
class Animal:
    def __init__(self, name):
        self.name = name
class Dog(Animal):
    def __init__(self, name):
          # super calls __init__ 
          # method from parent class
          super().__init__(name)
Case Study: Building Software in Python

Let's practice!

Case Study: Building Software in Python

Preparing Video For Download...