Khái niệm và Ứng dụng Cơ bản của Kế thừa, Đóng gói, Đa hình trong Python

Trong lập trình hướng đối tượng, các nguyên lý kế thừa, đóng gói và đa hình tạo nên nền tảng cho thiết kế phần mềm hiệu quả. Dưới đây là phân tích chi tiết về từng khái niệm cùng ví dụ minh họa trong Python.

1. Kế thừa
Kế thừa cho phép một lớp con kế thừa thuộc tính và phương thức từ lớp cha. Lớp con có thể mở rộng hoặc ghi đè hành vi của lớp cha.

class Creature:
    def __init__(self, species_name):
        self.species = species_name
    
    def produce_sound(self):
        print("Sound from generic creature")

class Mammal(Creature):
    def produce_sound(self):
        print("Mammal vocalization")

Trong ví dụ này, Mammal kế thừa từ Creature và ghi đè phương thức produce_sound.

2. Đóng gói
Đóng gói bảo vệ trạng thái nội bộ của đối tượng bằng cách ẩn thuộc tính và chỉ cho phép truy cập qua phương thức công khai.

class FinancialAccount:
    def __init__(self, account_owner, starting_balance=0):
        self._account_owner = account_owner
        self._current_balance = starting_balance
    
    def add_funds(self, amount):
        if amount > 0:
            self._current_balance += amount
            return True
        return False
    
    def check_balance(self):
        return self._current_balance

Các thuộc tính _account_owner_current_balance được đánh dấu là "private" (dùng tiền tố gạch dưới) và chỉ có thể thao tác qua phương thức add_fundscheck_balance.

3. Đa hình
Đa hình cho phép các đối tượng khác lớp phản hồi khác nhau với cùng một phương thức, tạo tính linh hoạt cho hệ thống.

class GeometricEntity:
    def calculate_surface(self):
        raise NotImplementedError("Subclasses must implement this method")

class CircleEntity(GeometricEntity):
    def __init__(self, radius):
        self.radius = radius
    def calculate_surface(self):
        return 3.14159 * self.radius ** 2

class RectangleEntity(GeometricEntity):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def calculate_surface(self):
        return self.width * self.height

def show_surface(entity):
    print(entity.calculate_surface())

circle = CircleEntity(7)
square = RectangleEntity(5, 8)
show_surface(circle)  # 153.93815
show_surface(square)  # 40

Thẻ: python-class-inheritance python-encapsulation python-polymorphism

Đăng vào ngày 22 tháng 7 lúc 23:07