Chapter2-Inheritance and Polymorphism PDF
Chapter2-Inheritance and Polymorphism PDF
data
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Alex Yarosh
Content Quality Analyst @ DataCamp
Core principles of OOP
Inheritance:
Extending functionality of existing code
Polymorphism:
Creating a uni ed interface
Encapsulation:
Bundling of data and methods
class MyClass:
# Define a class attribute
CLASS_ATTR_NAME = attr_value
...
class MyClass:
MyClass.my_awesome_method(args...)
Alex Yarosh
Content Quality Analyst @ DataCamp
Code reuse
New class functionality = Old class functionality + extra
__main__.SavingsAccount
1000
True False
True True
Alex Yarosh
Content Quality Analyst @ DataCamp
OBJECT-ORIENTED PROGRAMMING IN PYTHON
What we have so far
class BankAccount:
def __init__(self, balance):
self.balance = balance
0.03
Can use the data from both the parent and the child class
class SavingsAccount(BankAccount):
# New functionality
def compute_interest(self, n_periods = 1):
return self.balance * ( (1 + self.interest_rate) ** n_periods - 1)
# Will call withdraw from CheckingAccount # Will call withdraw from BankAccount
check_acct.withdraw(200) bank_acct.withdraw(200)