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

更新時間:2022-08-12

3K+ 次瀏覽

開啟你的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.