ใช่ Python รองรับการสืบทอดหลายรายการ
เช่นเดียวกับ C++ คลาสสามารถได้มาจากคลาสพื้นฐานมากกว่าหนึ่งคลาสใน Python สิ่งนี้เรียกว่าการสืบทอดหลายรายการ
ในการสืบทอดหลายรายการ คุณลักษณะของคลาสพื้นฐานทั้งหมดจะถูกสืบทอดไปยังคลาสที่ได้รับ
ตัวอย่าง
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 จะสืบทอดคลาส Animal
- Animal เป็นคลาสหลักหรือที่เรียกว่า super class หรือ base class
- Bird เป็นคลาสย่อยที่เรียกว่าคลาสย่อยหรือคลาสที่ได้รับ
เมธอด issubclass ช่วยให้มั่นใจได้ว่า Bird เป็นคลาสย่อยของคลาส Animal
ผลลัพธ์
True True It eats insects. It sleeps in the night. It flies in the sky. It sings a song.