Class inheritance

Object-Oriented Programming in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

Code reuse

Object-Oriented Programming in Python

Code reuse

 

1. Someone has already done it

 

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

logos of several python packages

Object-Oriented Programming in Python

Code reuse

 

1. Someone has already done it

 

2. DRY: Don't Repeat Yourself

various gui elements

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

Object-Oriented Programming in Python

Inheritance

 

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

Object-Oriented Programming in Python

account class

Object-Oriented Programming in Python

savings account inherited from account

Object-Oriented Programming in Python

two classes inherited from account

Object-Oriented Programming in Python

modified method in checking account

Object-Oriented Programming in Python

Implementing class inheritance

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

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

# Empty class inherited from BankAccount
class SavingsAccount(BankAccount):
    pass

class MyChild(MyParent):
   # Do stuff here
  • MyParent: class whose functionality is being extended/inherited
  • MyChild: class that will inherit the functionality and add more
Object-Oriented Programming in Python

Child class has all of the 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)
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
Object-Oriented Programming in Python

Let's practice!

Object-Oriented Programming in Python

Preparing Video For Download...