如何組織我的 Python 程式碼以便更容易更改基類?
在學習如何更改基類之前,讓我們首先了解 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
為了更容易更改基類,你需要將基類賦值給一個別名,並從此別名派生。之後,更改分配給別名的值。
如果你想決定使用哪個基類,上述步驟也有效。例如,讓我們看看顯示相同的程式碼片段:
class Base: ... BaseAlias = Base class Derived(BaseAlias):
廣告