在 Python 中,继承一个类是通过在定义子类时在类名后的括号中指定父类来实现的。以下是继承的基本语法和示例:
基本语法
class 子类名(父类名):
# 子类的代码
示例说明
-
单继承(一个子类继承一个父类):
class ParentClass: def parent_method(self): print("这是父类的方法") class ChildClass(ParentClass): # 继承ParentClass def child_method(self): print("这是子类的方法") # 使用 child = ChildClass() child.parent_method() # 调用继承的父类方法 child.child_method() # 调用子类方法
-
方法重写(子类覆盖父类方法):
class ParentClass: def method(self): print("父类的method") class ChildClass(ParentClass): def method(self): # 重写父类方法 print("子类重写的method") # 使用 child = ChildClass() child.method() # 输出:子类重写的method
-
调用父类方法(使用
super()
):class ParentClass: def method(self): print("父类的method") class ChildClass(ParentClass): def method(self): super().method() # 先调用父类的method print("子类新增的内容") # 使用 child = ChildClass() child.method() # 输出: # 父类的method # 子类新增的内容
-
多继承(一个子类继承多个父类):
class Father: def method(self): print("Father的方法") class Mother: def method(self): print("Mother的方法") class Child(Father, Mother): # 多继承 pass # 使用(按继承顺序从左到右优先调用) child = Child() child.method() # 输出:Father的方法(因为Father在继承列表的个)
关键注意事项
- 继承顺序:多继承时,方法调用按
MRO(Method Resolution Order)
规则(通常从左到右)。 super()
:用于调用父类的方法,尤其在多继承中能避免重复调用。isinstance()
和issubclass()
:可用来检查实例与类、类与类的关系。
如果有更复杂的需求(如抽象基类、混入类等),可以进一步扩展学习!
// 来源:https://www.nzw6.com