Continuing from the previous article, after understanding class definitions and function definitions, we begin to learn about object-oriented programming, which has three main characteristics: encapsulation, inheritance, and polymorphism. Let’s learn about each of these:
๐ Characteristic 1: Encapsulation
The core idea: encapsulating data and methods together, hiding internal implementation details
Detailed case: ATM machine
class ATM: def __init__(self, initial_amount): self.__balance = initial_amount # Private attribute (with __) self.__password = "123456" # Private attribute self.__today_withdrawal_count = 0 # Private attribute self.__transaction_record = [] # Private attribute
def __validate_password(self, input_password): """Private method: validate password""" return input_password == self.__password
def __record_transaction(self, type, amount): """Private method: record transaction""" from datetime import datetime time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.__transaction_record.append({ 'time': time, 'type': type, 'amount': amount, 'balance': self.__balance })
def deposit(self, amount, password): """Public method: deposit""" print(f"\n{'='*40}") print(f"๐ฐ Deposit operation") print(f"{'='*40}")
if not self.__validate_password(password): print("โ Incorrect password!") return False
if amount <= 0: print("โ Deposit amount must be greater than 0") return False
if amount > 100000: print("โ Single deposit cannot exceed 100,000") return False
self.__balance += amount self.__record_transaction("Deposit", amount) print(f"โ
Successfully deposited {amount} yuan") print(f"๐ฐ Current balance: {self.__balance} yuan") return True
def withdraw(self, amount, password): """Public method: withdraw""" print(f"\n{'='*40}") print(f"๐ต Withdrawal operation") print(f"{'='*40}")
# Check password if not self.__validate_password(password): print("โ Incorrect password!") return False
# Check amount if amount <= 0: print("โ Withdrawal amount must be greater than 0") return False
if amount % 100 != 0: print("โ Withdrawal amount must be a multiple of 100") return False
# Check balance if amount > self.__balance: print(f"โ Insufficient balance!") print(f"๐ฐ Current balance: {self.__balance} yuan") return False
# Check daily limit if self.__today_withdrawal_count >= 3: print("โ Daily withdrawal limit reached (3 times)") return False
if amount > 5000: print("โ Single withdrawal cannot exceed 5,000 yuan") return False
# Execute withdrawal self.__balance -= amount self.__today_withdrawal_count += 1 self.__record_transaction("Withdrawal", amount) print(f"โ
Successfully withdrew {amount} yuan") print(f"๐ฐ Current balance: {self.__balance} yuan") print(f"๐ Today's withdrawals: {self.__today_withdrawal_count} times") return True
def check_balance(self, password): """Public method: check balance""" print(f"\n{'='*40}") print(f"๐ Balance inquiry") print(f"{'='*40}")
if not self.__validate_password(password): print("โ Incorrect password!") return None
print(f"๐ฐ Current balance: {self.__balance} yuan") print(f"๐ Today's withdrawals: {self.__today_withdrawal_count} times") return self.__balance
def change_password(self, old_password, new_password): """Public method: change password""" print(f"\n{'='*40}") print(f"๐ Change password") print(f"{'='*40}")
if not self.__validate_password(old_password): print("โ Old password is incorrect!") return False
if len(new_password) < 6: print("โ New password must be at least 6 characters long") return False
if new_password.isdigit() and len(set(new_password)) < 3: print("โ Password is too simple, please use a more complex password") return False
self.__password = new_password print("โ
Password changed successfully") return True
def view_transaction_record(self, password): """Public method: view transaction record""" print(f"\n{'='*40}") print(f"๐ Transaction record") print(f"{'='*40}")
if not self.__validate_password(password): print("โ Incorrect password!") return None
if not self.__transaction_record: print("No transaction records available") return []
for i, record in enumerate(self.__transaction_record, 1): print(f"\nใRecord {i}ใ") print(f"Time: {record['time']}") print(f"Type: {record['type']}") print(f"Amount: {record['amount']} yuan") print(f"Balance: {record['balance']} yuan") return self.__transaction_record
# ========== Example Usage ==========if __name__ == "__main__": print("๐ฆ Welcome to the ATM\n")
# Create ATM account my_account = ATM(10000)
# Scenario 1: Normal deposit my_account.deposit(5000, "123456")
# Scenario 2: Incorrect password my_account.withdraw(1000, "wrong_password")
# Scenario 3: Normal withdrawal my_account.withdraw(2000, "123456")
# Scenario 4: Insufficient balance my_account.withdraw(20000, "123456")
# Scenario 5: Multiple withdrawal test my_account.withdraw(1000, "123456") my_account.withdraw(1000, "123456") my_account.withdraw(1000, "123456") # The 4th time will be rejected
# Scenario 6: Check balance my_account.check_balance("123456")
# Scenario 7: Attempt to directly modify balance (will fail) print(f"\n{'='*40}") print(f"๐ The protective effect of encapsulation") print(f"{'='*40}") try: my_account.__balance = 999999 # Cannot access print(my_account.__balance) except AttributeError: print("โ Cannot directly access private attribute __balance") print("โ
Data is protected! Must access through public methods")
# Scenario 8: Change password my_account.change_password("123456", "654321")
# Scenario 9: View transaction record my_account.view_transaction_record("654321")
๐ฏ Benefits of Encapsulation
- Data security: balance and password cannot be modified directly
- Logical protection: all operations are validated
- Easy maintenance: internal modifications do not affect external usage
๐งฌ Characteristic 2: Inheritance
The core idea: subclasses can inherit all properties and methods of the parent class
Detailed case: Company employee management system
from datetime import datetime
# Parent class: Employee base classclass Employee: company_name = "Innovative Technology Co., Ltd." total_employees = 0
def __init__(self, name, employee_id, base_salary, hire_date=None): self.name = name self.employee_id = employee_id self.base_salary = base_salary self.hire_date = hire_date or datetime.now().strftime("%Y-%m-%d") self.attendance_days = 0 Employee.total_employees += 1 print(f"โ
{name} hired successfully! Employee ID: {employee_id}")
def clock_in(self): """All employees need to clock in""" self.attendance_days += 1 print(f"๐ค {self.name} has clocked in (Day {self.attendance_days})")
def take_leave(self, days, reason): """All employees can take leave""" print(f"๐ {self.name} is taking leave for {days} days") print(f" Reason: {reason}")
def calculate_salary(self): """Basic salary calculation (subclasses can override)""" attendance_bonus = self.attendance_days * 50 return self.base_salary + attendance_bonus
def display_info(self): """Display basic employee information""" print(f"\n{'='*50}") print(f"๐ค Employee Information") print(f"{'='*50}") print(f"Name: {self.name}") print(f"Employee ID: {self.employee_id}") print(f"Hire Date: {self.hire_date}") print(f"Attendance Days: {self.attendance_days} days") print(f"This Month's Salary: {self.calculate_salary()} yuan") print(f"Company: {Employee.company_name}") print(f"{'='*50}")
@classmethod def get_total_employees(cls): return cls.total_employees
# Subclass 1: Programmerclass Programmer(Employee): def __init__(self, name, employee_id, base_salary, programming_language, tech_level="Junior"): super().__init__(name, employee_id, base_salary) self.programming_language = programming_language self.tech_level = tech_level self.code_lines = 0 self.bug_count = 0 self.project_list = []
def write_code(self, project_name, lines): """Method unique to programmers""" self.code_lines += lines if project_name not in self.project_list: self.project_list.append(project_name) print(f"๐ป {self.name} wrote {lines} lines of {self.programming_language} code for project ใ{project_name}ใ") print(f" Total code: {self.code_lines} lines")
def fix_bug(self, count=1): """Method unique to programmers""" if self.bug_count > 0: fixed_count = min(count, self.bug_count) self.bug_count -= fixed_count print(f"๐ {self.name} fixed {fixed_count} bugs, {self.bug_count} remaining") else: print(f"โจ {self.name} has no bugs to fix")
def code_review(self, reviewer): """Method unique to programmers""" print(f"๐ {self.name} is reviewing {reviewer}'s code")
def calculate_salary(self): """Override parent class method""" base_salary = super().calculate_salary()
# Technical level coefficient level_coefficient = {"Junior": 1.0, "Intermediate": 1.3, "Senior": 1.6, "Expert": 2.0} tech_allowance = self.base_salary * (level_coefficient.get(self.tech_level, 1.0) - 1.0)
# Code bonus (500 yuan for every 1000 lines) code_bonus = (self.code_lines // 1000) * 500
# Bug penalty (100 yuan for each bug) bug_penalty = self.bug_count * 100
# Project bonus (1000 yuan for each project) project_bonus = len(self.project_list) * 1000
total_salary = base_salary + tech_allowance + code_bonus + project_bonus - bug_penalty return total_salary
def display_info(self): """Override parent class method""" super().display_info() print(f"๐ป Programming Language: {self.programming_language}") print(f"โญ Technical Level: {self.tech_level}") print(f"๐ Code Lines: {self.code_lines}") print(f"๐ Bug Count: {self.bug_count}") print(f"๐ Projects Involved: {len(self.project_list)}") if self.project_list: for project in self.project_list: print(f" - {project}") print(f"{'='*50}\n")
# Subclass 2: Salespersonclass Salesperson(Employee): def __init__(self, name, employee_id, base_salary, sales_region): super().__init__(name, employee_id, base_salary) self.sales_region = sales_region self.sales_amount = 0 self.client_list = [] self.order_count = 0
def complete_order(self, client_name, amount): """Method unique to salespersons""" self.sales_amount += amount self.order_count += 1 if client_name not in self.client_list: self.client_list.append(client_name) print(f"๐ {self.name} completed an order") print(f" Client: {client_name}") print(f" Amount: {amount} yuan") print(f" Total Sales: {self.sales_amount} yuan")
def visit_client(self, client_name): """Method unique to salespersons""" print(f"๐ค {self.name} is visiting client: {client_name}")
def calculate_salary(self): """Override parent class method""" base_salary = super().calculate_salary() commission = self.sales_amount * 0.1 # 10% commission order_bonus = self.order_count * 200 # 200 yuan per order total_salary = base_salary + commission + order_bonus return total_salary
def display_info(self): """Override parent class method""" super().display_info() print(f"๐บ๏ธ Sales Region: {self.sales_region}") print(f"๐ต Sales Amount: {self.sales_amount} yuan") print(f"๐ฆ Order Count: {self.order_count}") print(f"๐ฅ Client Count: {len(self.client_list)}") print(f"{'='*50}\n")
# Subclass 3: Managerclass Manager(Employee): def __init__(self, name, employee_id, base_salary, managed_department): super().__init__(name, employee_id, base_salary) self.managed_department = managed_department self.subordinate_list = [] self.meeting_count = 0
def add_subordinate(self, employee_object): """Method unique to managers""" self.subordinate_list.append(employee_object) print(f"๐ฅ {employee_object.name} has become a subordinate of {self.name}")
def hold_meeting(self, meeting_topic): """Method unique to managers""" self.meeting_count += 1 print(f"\n๐ข {self.name} is holding the {self.meeting_count}th meeting") print(f"Department: {self.managed_department}") print(f"Topic: {meeting_topic}") print(f"Participants:") for subordinate in self.subordinate_list: print(f" โ {subordinate.name}")
def performance_review(self, employee_object, rating): """Method unique to managers""" print(f"๐ {self.name} is conducting a performance review for {employee_object.name}") print(f" Rating: {rating}/100") if rating >= 90: print(f" Evaluation: Excellent") elif rating >= 70: print(f" Evaluation: Good") else: print(f" Evaluation: Needs Improvement")
def calculate_salary(self): """Override parent class method""" base_salary = super().calculate_salary() management_allowance = len(self.subordinate_list) * 1000 # 1000 yuan for each subordinate meeting_allowance = self.meeting_count * 500 # 500 yuan for each meeting total_salary = base_salary + management_allowance + meeting_allowance return total_salary
def display_info(self): """Override parent class method""" super().display_info() print(f"๐๏ธ Managed Department: {self.managed_department}") print(f"๐ฅ Number of Subordinates: {len(self.subordinate_list)}") print(f"๐ข Number of Meetings: {self.meeting_count}") print(f"{'='*50}\n")
# ========== Example Usage ==========if __name__ == "__main__": print("๐ข Welcome to Innovative Technology Co., Ltd.\n") print("="*50)
# Create employees programmer1 = Programmer("Zhang San", "DEV001", 15000, "Python", "Senior") programmer2 = Programmer("Li Si", "DEV002", 12000, "Java", "Intermediate") salesperson1 = Salesperson("Wang Wu", "SALES001", 8000, "East China") salesperson2 = Salesperson("Zhao Liu", "SALES002", 8000, "North China") manager1 = Manager("Qian Qi", "MGR001", 20000, "Technical Department") manager2 = Manager("Sun Ba", "MGR002", 18000, "Sales Department")
print(f"\nCurrent total employees: {Employee.get_total_employees()}\n")
# Establish management relationships print("="*50) print("๐ Establishing management relationships") print("="*50) manager1.add_subordinate(programmer1) manager1.add_subordinate(programmer2) manager2.add_subordinate(salesperson1) manager2.add_subordinate(salesperson2)
# First week work print(f"\n{'='*50}") print("๐
First week work records") print(f"{'='*50}")
# All employees clock in print("\nโฐ Monday clock-in:") for _ in range(5): # Work for 5 days programmer1.clock_in() programmer2.clock_in() salesperson1.clock_in() salesperson2.clock_in() manager1.clock_in() manager2.clock_in()
# Programmer work print(f"\n๐ป Programmer work:") programmer1.write_code("E-commerce platform", 3000) programmer1.write_code("Payment system", 2000) programmer1.bug_count = 3 programmer1.fix_bug(2) programmer1.code_review("Li Si")
print() programmer2.write_code("E-commerce platform", 2500) programmer2.write_code("Recommendation system", 1800)
# Salesperson work print(f"\n๐ผ Salesperson work:") salesperson1.visit_client("Alibaba") salesperson1.complete_order("Alibaba", 150000) salesperson1.complete_order("Tencent", 120000)
print() salesperson2.visit_client("ByteDance") salesperson2.complete_order("ByteDance", 180000) salesperson2.complete_order("Meituan", 90000)
# Manager work print(f"\n๐ Manager work:") manager1.hold_meeting("Project progress review") manager1.hold_meeting("Technical sharing session") manager1.performance_review(programmer1, 95)
print() manager2.hold_meeting("Sales strategy discussion") manager2.performance_review(salesperson1, 92)
# Leave records print(f"\n๐ Leave records:") programmer2.take_leave(1, "Family illness") salesperson2.take_leave(0.5, "Afternoon dental appointment")
# End of month salary settlement print(f"\n{'='*50}") print("๐ฐ End of month salary settlement") print(f"{'='*50}")
all_employees = [programmer1, programmer2, salesperson1, salesperson2, manager1, manager2] total_salary = 0 for employee in all_employees: employee.display_info() total_salary += employee.calculate_salary()
print(f"{'='*50}") print(f"๐ฐ Total salary for the month: {total_salary} yuan") print(f"๐ฅ Total employees: {Employee.get_total_employees()}") print(f"{'='*50}")
# Inheritance relationship verification print(f"\n{'='*50}") print("๐ Inheritance relationship verification") print(f"{'='*50}") print(f"Is programmer1 an employee? {isinstance(programmer1, Employee)}") print(f"Is programmer1 a programmer? {isinstance(programmer1, Programmer)}") print(f"Is programmer1 a salesperson? {isinstance(programmer1, Salesperson)}") print(f"Is programmer1 a manager? {isinstance(programmer1, Manager)}")
๐ฏ Benefits of Inheritance
- Code reuse: methods like clocking in and taking leave do not need to be rewritten
- Strong extensibility: adding new employee types is easy
- Clear hierarchy: establishes “is-a” relationships
๐ญ Characteristic 3: Polymorphism
The core idea: the same method call produces different behaviors for different objects.
Detailed case: Zoo management system:
from datetime import datetimeimport random
# Parent class: Animalclass Animal: total_animals = 0
def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender self.hunger_level = 50 # 0-100 self.health_level = 100 # 0-100 self.mood = "Normal" # Happy/Normal/Unhappy Animal.total_animals += 1
def eat(self): """Every animal eats, but the food differs (polymorphism)""" pass # Subclass must implement
def make_sound(self): """Every animal makes a sound, but the sound differs (polymorphism)""" pass # Subclass must implement
def sleep(self): """All animals sleep""" self.health_level = min(100, self.health_level + 10) print(f"๐ด {self.name} is sleeping, health level restored to {self.health_level}")
def update_status(self): """Update animal status""" # Hunger level affects mood if self.hunger_level > 70: self.mood = "Unhappy" self.health_level -= 5 elif self.hunger_level > 40: self.mood = "Normal" else: self.mood = "Happy"
def display_status(self): """Display animal status""" self.update_status() print(f"\n{'='*40}") print(f"๐ {self.name}'s status") print(f"{'='*40}") print(f"Type: {self.__class__.__name__}") print(f"Age: {self.age} years") print(f"Gender: {self.gender}") print(f"Hunger Level: {self.hunger_level}/100", end="") if self.hunger_level > 70: print(" ๐ซ Very hungry") elif self.hunger_level > 40: print(" ๐ A bit hungry") else: print(" ๐ Full") print(f"Health Level: {self.health_level}/100", end="") if self.health_level > 80: print(" ๐ช Healthy") elif self.health_level > 50: print(" ๐ Normal") else: print(" ๐ค Needs a doctor") print(f"Mood: {self.mood}") print(f"{'='*40}")
# Subclass 1: Dogclass Dog(Animal): def __init__(self, name, age, gender, breed): super().__init__(name, age, gender) self.breed = breed self.toy_list = []
def eat(self): """Dogs eat dog food""" print(f"๐ {self.name}({self.breed}) happily eats dog food") print(f" Crunch crunch, so delicious!") self.hunger_level = max(0, self.hunger_level - 35) print(f" Hunger Level: {self.hunger_level}")
def make_sound(self): """Dogs bark""" sound = random.choice(["Woof woof!", "Wang wang!", "Awoo๏ฝ"]) print(f"๐ {self.name}: {sound}")
def wag_tail(self): """Unique behavior of dogs""" print(f"๐ {self.name} happily wags its tail and spins around")
def play_with_toy(self, toy): """Unique behavior of dogs""" if toy not in self.toy_list: self.toy_list.append(toy) print(f"๐พ {self.name} is playing with {toy}") self.mood = "Happy"
# Subclass 2: Catclass Cat(Animal): def __init__(self, name, age, gender, fur_color): super().__init__(name, age, gender) self.fur_color = fur_color
def eat(self): """Cats eat cat food""" print(f"๐ฑ {self.name}({self.fur_color} fur) elegantly tastes cat food") print(f" Mmm๏ฝ tastes good") self.hunger_level = max(0, self.hunger_level - 30) print(f" Hunger Level: {self.hunger_level}")
def make_sound(self): """Cats meow""" sound = random.choice(["Meow meow๏ฝ", "Meow๏ฝ", "Mew๏ฝ"]) print(f"๐ฑ {self.name}: {sound}")
def scratch_sofa(self): """Unique behavior of cats""" print(f"๐ฑ {self.name} is scratching the sofa (please forgive it)")
def groom(self): """Unique behavior of cats""" print(f"๐ฑ {self.name} is seriously grooming itself")
# Subclass 3: Birdclass Bird(Animal): def __init__(self, name, age, gender, feather_color): super().__init__(name, age, gender) self.feather_color = feather_color self.flight_distance = 0
def eat(self): """Birds eat bird food""" print(f"๐ฆ {self.name}({self.feather_color} feathers) pecks at bird food") print(f" Chirp chirp, delicious") self.hunger_level = max(0, self.hunger_level - 25) print(f" Hunger Level: {self.hunger_level}")
def make_sound(self): """Birds chirp""" sound = random.choice(["Chirp chirp๏ฝ", "Tweet๏ฝ", "tweet๏ฝ"]) print(f"๐ฆ {self.name}: {sound}")
def fly(self, distance): """Unique behavior of birds""" self.flight_distance += distance print(f"๐ฆ {self.name} flew {distance} meters in the sky") print(f" Total flight: {self.flight_distance} meters")
# Subclass 4: Rabbitclass Rabbit(Animal): def __init__(self, name, age, gender, breed): super().__init__(name, age, gender) self.breed = breed
def eat(self): """Rabbits eat carrots""" print(f"๐ฐ {self.name}({self.breed}) nibbles on a carrot") print(f" Crunch crunch, the carrot is so sweet!") self.hunger_level = max(0, self.hunger_level - 28) print(f" Hunger Level: {self.hunger_level}")
def make_sound(self): """Rabbits are mostly silent""" print(f"๐ฐ {self.name}: ...(Rabbits are quiet)")
def hop(self): """Unique behavior of rabbits""" print(f"๐ฐ {self.name} hops around, so cute")
# Caretaker class (demonstrating the core of polymorphism)class Caretaker: def __init__(self, name): self.name = name self.responsible_animals = [] print(f"๐จ๐พ Caretaker {name} is on duty\n")
def add_responsible_animal(self, animal): """Add responsible animal""" self.responsible_animals.append(animal) print(f"๐ {self.name} is now responsible for taking care of {animal.name}")
def feed(self, animal): """Polymorphism: unified feeding interface, different animals eat different food""" print(f"\n{'='*40}") print(f"๐จ๐พ {self.name} is feeding {animal.name}") print(f"{'='*40}") animal.eat() # โ Polymorphism: different animals call different eat methods
def interact(self, animal): """Polymorphism: unified interaction interface, different animals have different reactions""" print(f"\n{'='*40}") print(f"๐จ๐พ {self.name} is interacting with {animal.name}") print(f"{'='*40}") animal.make_sound() # โ Polymorphism: different animals make different sounds
def batch_feed(self): """The power of polymorphism: uniformly handle different types of animals""" print(f"\n{'='*50}") print(f"๐จ๐พ {self.name} starts feeding all animals") print(f"{'='*50}") for animal in self.responsible_animals: self.feed(animal) # โ The same method, different behaviors
print(f"\nโ
All animals have been fed!")
def animal_show(self): """Polymorphism demonstration: let all animals perform (make sounds)""" print(f"\n{'='*50}") print(f"๐ช Animal show time!") print(f"{'='*50}") for animal in self.responsible_animals: self.interact(animal) # โ The same method, different behaviors
def health_check(self): """Check the health status of all animals""" print(f"\n{'='*50}") print(f"๐ฅ {self.name} is conducting a health check") print(f"{'='*50}") for animal in self.responsible_animals: animal.display_status()
# ========== Example Usage ==========if __name__ == "__main__": print("๐๏ธ Welcome to Happy Zoo\n") print("="*50)
# Create various animals dog1 = Dog("Wang Cai", 3, "Male", "Golden Retriever") cat1 = Cat("Mi Mi", 2, "Female", "Orange") bird1 = Bird("Xiao Huang", 1, "Male", "Yellow") rabbit1 = Rabbit("Xiao Bai", 1, "Female", "Lop-eared")
dog2 = Dog("Da Huang", 5, "Male", "Husky") cat2 = Cat("Xiao Hei", 3, "Male", "Black")
print()
# Create caretakers caretaker1 = Caretaker("Zhang San") caretaker2 = Caretaker("Li Si")
print()
# Assign animals print("="*50) print("๐ Assigning animals") print("="*50) caretaker1.add_responsible_animal(dog1) caretaker1.add_responsible_animal(cat1) caretaker1.add_responsible_animal(bird1)
caretaker2.add_responsible_animal(rabbit1) caretaker2.add_responsible_animal(dog2) caretaker2.add_responsible_animal(cat2)
# Scenario 1: Batch feeding (the power of polymorphism) caretaker1.batch_feed()
# Scenario 2: Animal show caretaker1.animal_show()
# Scenario 3: Individual interaction print(f"\n{'='*50}") print("๐ฎ Special interaction time") print(f"{'='*50}")
print(f"\n๐จ๐พ Zhang San plays with dog1:") dog1.wag_tail() dog1.play_with_toy("Frisbee") dog1.play_with_toy("Ball")
print(f"\n๐จ๐พ Zhang San teases cat1:") cat1.groom() cat1.scratch_sofa()
print(f"\n๐จ๐พ Li Si watches bird fly:") bird1.fly(50) bird1.fly(30)
print(f"\n๐จ๐พ Li Si plays with rabbit1:") rabbit1.hop()
# Scenario 4: Health check caretaker1.health_check()
# Scenario 5: Demonstrating the essence of polymorphism print(f"\n{'='*50}") print("๐ Demonstrating the essence of polymorphism") print(f"{'='*50}")
print("\nHandling animals with the same function:")
def let_animals_eat_and_make_sound(animal_object): """This function does not need to know what kind of animal it is""" print(f"\nHandling animal: {animal_object.name}") animal_object.eat() # โ Polymorphism: call the corresponding eat method based on the actual object type animal_object.make_sound() # โ Polymorphism
all_animals = [dog1, cat1, bird1, rabbit1] for animal in all_animals: let_animals_eat_and_make_sound(animal)
# Statistics print(f"\n{'='*50}") print(f"๐ Zoo Statistics") print(f"{'='*50}") print(f"Total Animals: {Animal.total_animals}") print(f"Number of Caretakers: 2")
print(f"\nโจ Polymorphism makes the code more flexible and easier to extend!") print(" When adding new animal types, the caretaker's code does not need to be modified")
๐ฏ Benefits of Polymorphism
- Unified interface: the feed() method can handle any animal
- Easy to extend: adding new animal types does not require modifying caretaker code
- Concise code: one method handles multiple situations