Select a Subtopic
Day 8: Object-Oriented Programming (OOP)
Master the concepts of OOP in Python and apply them through exercises.
Topics:
- Classes and Objects
- Constructors (`__init__`)
- Methods
- Inheritance
- Polymorphism
Code Examples
Create a Class to Represent a Bank Account:
Define a BankAccount
class with methods to deposit and withdraw money.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited {amount}. New balance is {self.balance}")
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
print(f"Withdrew {amount}. New balance is {self.balance}")
else:
print("Insufficient balance")
# Example usage:
account = BankAccount("John Doe", 1000)
account.deposit(500)
account.withdraw(200)
Implement Inheritance:
Create a SavingsAccount
class that inherits from BankAccount
.
1
2
3
4
5
6
7
8
9
10
11
12
13
class SavingsAccount(BankAccount):
def __init__(self, account_holder, balance=0, interest_rate=0.02):
super().__init__(account_holder, balance)
self.interest_rate = interest_rate
def apply_interest(self):
interest = self.balance * self.interest_rate
self.balance += interest
print(f"Applied interest: {interest}. New balance is {self.balance}")
# Example usage:
savings_account = SavingsAccount("Jane Doe", 1000, 0.05)
savings_account.apply_interest()
Polymorphism Example:
Demonstrate polymorphism by creating different types of accounts with similar methods but different behaviors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CheckingAccount(BankAccount):
def __init__(self, account_holder, balance=0):
super().__init__(account_holder, balance)
def withdraw(self, amount):
fee = 5 # Checking account has a withdrawal fee
if self.balance >= (amount + fee):
self.balance -= (amount + fee)
print(f"Withdrew {amount} with a fee of {fee}. New balance is {self.balance}")
else:
print("Insufficient balance including fee")
# Example usage:
checking_account = CheckingAccount("John Smith", 1000)
checking_account.withdraw(100)
Summary:
- Create classes and objects in Python.
- Use constructors (`__init__`) to initialize objects.
- Define methods to encapsulate behaviors.
- Apply inheritance to extend functionality.
- Use polymorphism to implement similar behavior across different classes.
Well done! You've completed Day 8.
Feel free to try out the exercises, and let me know if you have any questions!