Tuesday, February 11, 2025

[Python] Lesson 40 – Multiple inheritance

-

Multiple inheritance trong Python cho phép một class có thể kế thừa từ nhiều class khác nhau. Cú pháp khai báo class với multiple inheritance là kết hợp các class cha trong dấu ngoặc đơn.

Cú pháp:

class ClassA:
    pass

class ClassB:
    pass

class ClassC(ClassA, ClassB):
    pass

Trong đó, ClassC kế thừa từ ClassAClassB.

Ví dụ 1:

class Animal:
    def __init__(self, name):
        self.name = name

class Flyable:
    def fly(self):
        print("Flying...")

class Bird(Animal, Flyable):
    pass

class Mammal(Animal):
    pass

class Bat(Mammal, Flyable):
    pass

bird = Bird("Sparrow")
bird.fly()  # Output: Flying...

bat = Bat("Fruit bat")
bat.fly()  # Output: Flying...

Trong ví dụ trên, Animal là class cha cơ bản, Flyable là class cha kế thừa về khả năng bay của động vật, BirdBat kế thừa từ AnimalFlyable, Bird là loài chim có khả năng bay, Bat là loài động vật có vú có khả năng bay.

Ví dụ 2:

class Car:
    def __init__(self, brand, model, color):
        self.brand = brand
        self.model = model
        self.color = color

class ElectricEngine:
    def __init__(self, power, battery_life):
        self.power = power
        self.battery_life = battery_life

    def charge(self):
        print("Charging the battery...")

class HybridCar(Car, ElectricEngine):
    def __init__(self, brand, model, color, power, battery_life, fuel_type):
        Car.__init__(self, brand, model, color)
        ElectricEngine.__init__(self, power, battery_life)
        self.fuel_type = fuel_type

    def get_info(self):
        print(f"Brand: {self.brand}\nModel: {self.model}\nColor: {self.color}")
        print(f"Power: {self.power} kW\nBattery life: {self.battery_life} hours")
        print(f"Fuel type: {self.fuel_type}")

    def drive(self):
        print("Starting the engine...")

car = HybridCar("Toyota", "Prius", "Blue", 60, 5, "Gasoline")
car.get_info()
car.charge()
car.drive()

Trong ví dụ này, ta có 3 class là Car, ElectricEngine, và HybridCar. Car là class cha đầu tiên và có các thuộc tính như brand, model, và color. ElectricEngine là class cha thứ hai và có các thuộc tính như powerbattery_life cùng với phương thức charge(). HybridCar là class con, kế thừa từ cả CarElectricEngine. Nó có thêm thuộc tính fuel_type và các phương thức riêng như get_info()drive(). Trong ví dụ này, ta sử dụng phương thức __init__() của cả 2 class cha để khởi tạo các thuộc tính tương ứng cho class con HybridCar.

Ví dụ trên giả định rằng ta đang xây dựng một chương trình quản lý thông tin xe hơi, bao gồm cả thông tin về động cơ điện và động cơ xăng. Các class CarElectricEngine là 2 class riêng biệt, nhưng chúng ta lại muốn kết hợp chúng lại với nhau để tạo ra class HybridCar. Ta sử dụng kỹ thuật multiple inheritance để kế thừa các thuộc tính và phương thức từ cả 2 class cha.

Ví dụ thực tế trong môi trường Linux để quản lý hệ thống:

import os
import shutil

class System:
    def __init__(self, name):
        self.name = name

    def create_directory(self, path):
        os.makedirs(path)

class FileOperations:
    def copy_file(self, source, destination):
        shutil.copyfile(source, destination)

class File(System, FileOperations):
    def __init__(self, name, path):
        System.__init__(self, name)
        self.path = path

file = File("file.txt", "/home/user/")
file.create_directory("/home/user/documents")
file.copy_file("/home/user/file.txt", "/home/user/documents/file.txt")

Trong ví dụ trên, System là class cha về các hoạt động liên quan đến hệ thống, FileOperations là class cha về các hoạt động liên quan đến file. File kế thừa từ cả SystemFileOperations để có thể thực hiện các hoạt động liên quan đến file và thư mục trong hệ thống.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

4,956FansLike
256FollowersFollow
223SubscribersSubscribe
spot_img

Related Stories