Class inheritance

Introduction to Object-Oriented Programming in Python

George Boorman

Curriculum Manager, DataCamp

Code reuse

 

1. Someone has already done it

 

  • Packages are great for fixed functionality
  • OOP is great for customizing functionality

logos of several python packages

Introduction to Object-Oriented Programming in Python

Code reuse

 

1. Someone has already done it

 

2. DRY: Don't Repeat Yourself

various gui elements

Introduction to Object-Oriented Programming in Python

Code reuse

 

1. Someone has already done it

 

2. DRY: Don't Repeat Yourself

don't use various gui elements

Introduction to Object-Oriented Programming in Python

Inheritance

 

$$\Large{\text{New class functionality = Old class functionality + extra}}$$

Introduction to Object-Oriented Programming in Python

Example hierarchy

BankAccount class

Introduction to Object-Oriented Programming in Python

Example hierarchy

SavingsAccount inheriting from BankAccount

Introduction to Object-Oriented Programming in Python

Example hierarchy

CheckingAccount also inheriting from BankAccount

Introduction to Object-Oriented Programming in Python

Example hierarchy

CheckingAccount has a modified withdraw method

Introduction to Object-Oriented Programming in Python

Implementing class inheritance

class BankAccount:
    def __init__(self, balance):
       self.balance = balance

    def withdraw(self, amount):
        self.balance -= amount


# Class inheriting from BankAccount class SavingsAccount(BankAccount): pass
  • BankAccount: Parent class whose functionality is being extended/inherited
  • SavingsAccount: Child/sub-class that will inherit the functionality and add more
Introduction to Object-Oriented Programming in Python

Child class has all of the parent data

# Constructor inherited from BankAccount
savings_acct = SavingsAccount(1000)
type(savings_acct)
__main__.SavingsAccount
# Attribute inherited from BankAccount
savings_acct.balance
1000
# Method inherited from BankAccount
savings_acct.withdraw(300)
Introduction to Object-Oriented Programming in Python

Inheritance: "is-a" relationship

A SavingsAccount is a BankAccount

(possibly with special features)

savings_acct = SavingsAccount(1000)
isinstance(savings_acct, SavingsAccount)
True
isinstance(savings_acct, BankAccount)
True

 

 

acct = BankAccount(500)
isinstance(acct, SavingsAccount)
False
isinstance(acct, BankAccount)
True
Introduction to Object-Oriented Programming in Python

Let's practice!

Introduction to Object-Oriented Programming in Python

Preparing Video For Download...