Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python รองรับ Multiple Inheritance หรือไม่?

ใช่ Python รองรับ Multiple Inheritance

เช่นเดียวกับ C++ คลาสหนึ่งสามารถสืบทอดมาจาก Base Class หลายตัวใน Python เรียกว่า Multiple Inheritance

ใน Multiple Inheritance คุณสมบัติของ Base Class ทั้งหมดจะถูกสืบทอดไปยัง Derived Class

ตัวอย่าง

class Animal:
    def eat(self):
        print("It eats insects.")
    def sleep(self):
        print("It sleeps in the night.")

class Bird(Animal):
    def fly(self):
        print("It flies in the sky.")
    def sing(self):
        print("It sings a song.")

print(issubclass(Bird, Animal))

koyal = Bird()
print(isinstance(koyal, Bird))

koyal.eat()
koyal.sleep()
koyal.fly()
koyal.sing()

ในตัวอย่างนี้ Bird Class สืบทอด Animal Class

  • Animal คือ Parent Class (Super Class / Base Class)
  • Bird คือ Child Class (Sub Class / Derived Class)

เมธอด issubclass ยืนยันว่า Bird เป็น Subclass ของ Animal Class

ผลลัพธ์

True
True
It eats insects.
It sleeps in the night.
It flies in the sky.
It sings a song.