继承是面向对象编程(oop)的一个重要特性,允许一个类(子类)从另一个类(父类)继承属性和方法。继承可以提高代码的重用性,增强程序的可扩展性和可维护性。
一、继承的作用
代码复用
子类继承父类的属性和方法,无需重复编写相同代码。逻辑层次清晰
通过继承关系表达对象间的从属关系,使代码更具结构性。增强扩展性
子类可以在继承父类的基础上扩展新的属性或方法,支持功能扩展。多态性
子类可以重写父类的方法,实现不同的行为。
二、继承的语法
在 python 中,继承通过类定义时括号中的父类名实现。
1. 单继承
子类继承单个父类:
class parent:
def greet(self):
print("hello from parent")
class child(parent):
pass # 子类继承了 parent 的所有属性和方法
# 使用子类
child = child()
child.greet() # 输出: hello from parent2. 多继承
子类继承多个父类:
class parent1:
def greet(self):
print("hello from parent1")
class parent2:
def greet(self):
print("hello from parent2")
class child(parent1, parent2):
pass
child = child()
child.greet() # 输出: hello from parent1 (根据继承顺序)多继承会按照方法解析顺序(mro)决定调用哪个父类的方法,可用
class.mro()或help(class)查看。
三、子类扩展
子类可以添加新的属性和方法,或者重写父类的方法。
1. 添加新功能
class parent:
def greet(self):
print("hello from parent")
class child(parent):
def say_goodbye(self):
print("goodbye from child")
child = child()
child.greet() # 输出: hello from parent
child.say_goodbye() # 输出: goodbye from child2. 重写父类方法
通过在子类中重新定义方法,覆盖父类的同名方法。
class parent:
def greet(self):
print("hello from parent")
class child(parent):
def greet(self):
print("hello from child") # 重写父类方法
child = child()
child.greet() # 输出: hello from child3. 调用父类方法
使用 super() 调用父类方法:
class parent:
def greet(self):
print("hello from parent")
class child(parent):
def greet(self):
super().greet() # 调用父类方法
print("hello from child")
child = child()
child.greet()
# 输出:
# hello from parent
# hello from child四、继承的特殊情况
1. 子类初始化父类
如果父类有 __init__ 方法,子类需要显式调用它。
class parent:
def __init__(self, name):
self.name = name
class child(parent):
def __init__(self, name, age):
super().__init__(name) # 调用父类的初始化方法
self.age = age
child = child("alice", 10)
print(child.name) # 输出: alice
print(child.age) # 输出: 102. 方法解析顺序(mro)
多继承时,python 按 mro 顺序查找方法。
class a:
def show(self):
print("a")
class b(a):
def show(self):
print("b")
class c(a):
pass
class d(b, c):
pass
print(d.mro())
# 输出: [<class '__main__.d'>, <class '__main__.b'>, <class '__main__.c'>, <class '__main__.a'>, <class 'object'>]
d = d()
d.show() # 输出: b五、抽象类与接口
通过继承实现抽象类和接口功能。
1. 抽象类
使用 abc 模块定义抽象类,要求子类必须实现特定方法。
from abc import abc, abstractmethod
class abstractclass(abc):
@abstractmethod
def abstract_method(self):
pass
class concreteclass(abstractclass):
def abstract_method(self):
print("implementation of abstract method")
obj = concreteclass()
obj.abstract_method() # 输出: implementation of abstract method2. 接口
通过继承实现类似接口的功能,强制子类遵循某些规则:
class interface:
def method(self):
raise notimplementederror("subclasses must implement this method")
class implementation(interface):
def method(self):
print("method implemented")
obj = implementation()
obj.method() # 输出: method implemented3. abc类
from abc import abc, abstractmethod, abstractclassmethod, abstractstaticmethod, abstractproperty
abc类
这是所有抽象基类的基类。@abstractmethod装饰器
用于定义抽象方法。子类必须实现该方法,否则无法实例化。@abstractclassmethod、@abstractstaticmethod和@abstractproperty
用于定义抽象的类方法、静态方法和属性。
抽象基类不能直接实例化,必须由子类实现所有抽象方法后才能实例化。所以上述的abstractclass类不能直接实例化,必须由concreteclass继承后实例化。
4. 使用方法
1. 定义抽象基类
from abc import abc, abstractmethod
# 定义抽象基类
class shape(abc):
@abstractmethod
def area(self):
"""计算面积"""
pass
@abstractmethod
def perimeter(self):
"""计算周长"""
pass
# 子类必须实现所有抽象方法
class rectangle(shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# 实例化子类
rect = rectangle(5, 10)
print(rect.area()) # 输出: 50
print(rect.perimeter()) # 输出: 30
# 尝试实例化抽象类会报错
# shape = shape() # typeerror: can't instantiate abstract class shape with abstract methods area, perimeter2. 抽象属性
使用 @abstractmethod 可以定义抽象属性。
from abc import *
class shape(abc):
@property
@abstractmethod
def name(self):
pass
class circle(shape):
@property
def name(self):
return "circle"
circle = circle()
print(circle.name) # 输出: circle3. 抽象静态方法和类方法
可以使用 @abstractstaticmethod 和 @abstractclassmethod。
from abc import *
class shape(abc):
@abstractstaticmethod
def description():
pass
@abstractclassmethod
def create(cls):
pass
class circle(shape):
@staticmethod
def description():
return "this is a circle"
@classmethod
def create(cls):
return cls()
circle = circle()
print(circle.description()) # 输出: this is a circle
circle_instance = circle.create()4. 检查子类是否实现抽象方法
如果子类没有实现抽象方法,尝试实例化子类会抛出 typeerror。
class incompleteshape(shape):
pass
# 会报错,因为 incompleteshape 没有实现 area 和 perimeter
# shape = incompleteshape() # typeerror: can't instantiate abstract class incompleteshape with abstract methods area, perimeter5. abc 的高级用法
1. 注册虚拟子类
通过 register() 方法,可以将一个类注册为抽象基类的虚拟子类,而无需继承抽象基类。
from abc import abc
class shape(abc):
pass
class polygon:
def sides(self):
return 4
# 将 polygon 注册为 shape 的虚拟子类
shape.register(polygon)
polygon = polygon()
print(isinstance(polygon, shape)) # 输出: true注册虚拟子类的行为仅限于 isinstance 和 issubclass 检查,不会强制实现抽象方法。
2. 定义混入类
抽象基类可以作为混入类,提供公共方法供子类继承,同时要求子类实现特定方法。
from abc import abc, abstractmethod
class jsonserializable(abc):
@abstractmethod
def to_json(self):
pass
def save(self, filepath):
with open(filepath, 'w') as f:
f.write(self.to_json())
class user(jsonserializable):
def __init__(self, name, age):
self.name = name
self.age = age
def to_json(self):
import json
return json.dumps({"name": self.name, "age": self.age})
user = user("alice", 30)
user.save("user.json")补充
方法解析顺序(mro,method resolution order)
方法解析顺序是 python 中确定在类继承体系中调用方法时的查找顺序的规则。mro 决定了在多继承场景下,当调用一个方法或属性时,python 应该从哪个类开始查找,并以什么顺序继续查找。
一、mro 的规则
深度优先、左到右
python 遵循一种称为 c3 线性化算法 的规则,该规则优先考虑深度优先,但会处理多继承中的冲突,确保类的继承关系是线性化的。排除重复
在继承树中,每个类只会被访问一次。保持继承顺序一致
子类的顺序会优先于父类,但父类的顺序会根据定义时的顺序进行保留。
二、查看 mro
在 python 中,可以使用以下方法查看一个类的 mro:
class.mro()方法:返回一个类的 mro 列表。help(class):显示类的信息,其中包含 mro。
示例:
class a:
def show(self):
print("a")
class b(a):
def show(self):
print("b")
class c(a):
pass
class d(b, c):
pass
print(d.mro())
# 输出: [<class '__main__.d'>, <class '__main__.b'>, <class '__main__.c'>, <class '__main__.a'>, <class 'object'>]
help(d)三、mro 的应用场景
1. 多继承中方法冲突的处理
多继承时,如果多个父类有同名方法,mro 会决定调用哪个父类的方法。
示例:
class a:
def show(self):
print("a")
class b(a):
def show(self):
print("b")
class c(a):
def show(self):
print("c")
class d(b, c): # 多继承
pass
d = d()
d.show()
# 输出: b
# mro 确定 `d -> b -> c -> a -> object`2. super() 的行为
super() 的调用遵循 mro。当使用 super() 调用方法时,会按照 mro 顺序继续查找下一个类的方法。
示例:
class a:
def greet(self):
print("hello from a")
class b(a):
def greet(self):
print("hello from b")
super().greet()
class c(a):
def greet(self):
print("hello from c")
super().greet()
class d(b, c):
def greet(self):
print("hello from d")
super().greet()
d = d()
d.greet()
# 输出:
# hello from d
# hello from b
# hello from c
# hello from amro 确保了 super() 按顺序调用各个父类的方法。
四、mro 的规则解析(c3 线性化算法)
c3 线性化算法是一种合并算法,确保继承顺序具有一致性和逻辑性。
步骤
- 从子类到父类按顺序依次列出所有父类。
- 确保子类优先于父类。
- 如果一个类有多个父类,按定义顺序列出父类。
- 保持父类中继承顺序的线性化。
示例:
class a: pass class b(a): pass class c(a): pass class d(b, c): pass print(d.mro()) # 输出: [<class '__main__.d'>, <class '__main__.b'>, <class '__main__.c'>, <class '__main__.a'>, <class 'object'>]
五、特殊情况
1. 菱形继承问题
菱形继承是指某个子类从两个父类继承,而两个父类又共同继承自一个祖先类的情况。python 的 mro 通过 c3 线性化算法解决了菱形继承问题,避免重复调用祖先类的方法。
示例:
class a:
def greet(self):
print("hello from a")
class b(a):
def greet(self):
print("hello from b")
super().greet()
class c(a):
def greet(self):
print("hello from c")
super().greet()
class d(b, c):
pass
d = d()
d.greet()
# 输出:
# hello from b
# hello from c
# hello from a2. 无法线性化的继承关系
如果多继承中的顺序不符合 c3 线性化规则,python 会报错。
示例:
class x: pass class y: pass class a(x, y): pass class b(y, x): pass class c(a, b): pass # 会报错,因为无法确定 mro 顺序
到此这篇关于python 继承详解(继承作用语法)的文章就介绍到这了,更多相关python 继承内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论