如何组织我的 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()
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
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):
广告