Python 是否支援多重繼承?
是的,Python 支援多重繼承。與 C++ 一樣,一個類可以在 Python 中從多個基類派生。這稱為多重繼承。
在多重繼承中,所有基類的特性都將被繼承到派生類。讓我們看看語法:
語法
Class Base1: Body of the class Class Base2: Body of the class Class Base3: Body of the class . . . Class BaseN: Body of the class Class Derived(Base1, Base2, Base3, … , BaseN): Body of the class
派生類從 Base1、Base2 和 Base3 類繼承。
示例
在下面的示例中,Bird 類繼承了 Animal 類。
Animal 是父類,也稱為超類或基類。
Bird 是子類,也稱為子類或派生類。
issubclass 方法確保 Bird 是 Animal 類的子類。
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()
輸出
True It eats insects. It sleeps in the night. It flies in the sky. It sings a song. True
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP