
在学习如何更改基类之前,让我们先了解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 类。
立即学习“Python免费学习笔记(深入)”;
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):
以上就是如何组织我的Python代码以便更容易更改基类?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号