python --super详解

本文深入探讨Python中的super函数,解释其在单继承和多继承场景下的工作原理,并通过具体示例展示了super函数如何帮助调用父类方法。
部署运行你感兴趣的模型镜像

说到 super, 大家可能觉得很简单呀,不就是用来调用父类方法的嘛。如果真的这么简单的话也就不会有这篇文章了,且听我细细道来。

约定

在开始之前我们来约定一下本文所使用的 Python 版本。默认用的是 Python 3,也就是说:本文所定义的类都是新式类。如果你用到是 Python 2 的话,记得继承 object:

# 默认, Python 3
class A:
    pass

# Python 2
class A(object):
    pass

Python 3 和 Python 2 的另一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :

# 默认,Python 3
class B(A):
    def add(self, x):
        super().add(x)

# Python 2
class B(A):
    def add(self, x):
        super(B, self).add(x)

所以,你如果用的是 Python 2 的话,记得将本文的 super() 替换为 suepr(Class, self) 。

如果还有其他不兼容 Python 2 的情况,我会在文中注明的。

单继承

在单继承中 super 就像大家所想的那样,主要是用来调用父类的方法的。

class A:
    def __init__(self):
        self.n = 2

    def add(self, m):
        print('self is {0} @A.add'.format(self))
        self.n += m


class B(A):
    def __init__(self):
        self.n = 3

    def add(self, m):
        print('self is {0} @B.add'.format(self))
        super().add(m)
        self.n += 3

你觉得执行下面代码后, b.n 的值是多少呢?

b = B()
b.add(2)
print(b.n)

执行结果如下:

self is <__main__.B object at 0x106c49b38> @B.add
self is <__main__.B object at 0x106c49b38> @A.add
8

这个结果说明了两个问题:

  • 1、super().add(m) 确实调用了父类 A 的 add 方法。
  • 2、super().add(m) 调用父类方法 def add(self, m) 时, 此时父类中 self 并不是父类的实例而是子类的实例, 所以 b.add(2) 之后的结果是 5 而不是 4 。

不知道这个结果是否和你想到一样呢?下面我们来看一个多继承的例子。

多继承

这次我们再定义一个 class C,一个 class D:

class C(A):
    def __init__(self):
        self.n = 4

    def add(self, m):
        print('self is {0} @C.add'.format(self))
        super().add(m)
        self.n += 4


class D(B, C):
    def __init__(self):
        self.n = 5

    def add(self, m):
        print('self is {0} @D.add'.format(self))
        super().add(m)
        self.n += 5

下面的代码又输出啥呢?

d = D()
d.add(2)
print(d.n)

这次的输出如下:

self is <__main__.D object at 0x10ce10e48> @D.add
self is <__main__.D object at 0x10ce10e48> @B.add
self is <__main__.D object at 0x10ce10e48> @C.add
self is <__main__.D object at 0x10ce10e48> @A.add
19

你说对了吗?你可能会认为上面代码的输出类似:

self is <__main__.D object at 0x10ce10e48> @D.add
self is <__main__.D object at 0x10ce10e48> @B.add
self is <__main__.D object at 0x10ce10e48> @A.add
15

为什么会跟预期的不一样呢?下面我们将一起来看看 super 的奥秘。

super 是个类

当我们调用 super() 的时候,实际上是实例化了一个 super 类。你没看错, super 是个类,既不是关键字也不是函数等其他数据结构:

>>> class A: pass
...
>>> s = super(A)
>>> type(s)
<class 'super'>
>>>

在大多数情况下, super 包含了两个非常重要的信息: 一个 MRO 以及 MRO 中的一个类。当以如下方式调用 super 时:

super(a_type, obj)

MRO 指的是 type(obj) 的 MRO, MRO 中的那个类就是 a_type , 同时 isinstance(obj, a_type) == True 。

当这样调用时:

super(type1, type2)

MRO 指的是 type2 的 MROMRO 中的那个类就是 type1 ,同时 issubclass(type2, type1) == True 。

那么, super() 实际上做了啥呢?简单来说就是:提供一个 MRO 以及一个 MRO 中的类 C , super() 将返回一个从 MRO 中 C 之后的类中查找方法的对象。

也就是说,查找方式时不是像常规方法一样从所有的 MRO 类中查找,而是从 MRO 的 tail 中查找。

举个例子, 有个 MRO:

[A, B, C, D, E, object]

下面的调用:

super(C, A).foo()

super 只会从 C 之后查找,即: 只会在 D 或 E 或 object 中查找 foo 方法。

多继承中 super 的工作方式

再回到前面的

d = D()
d.add(2)
print(d.n)

现在你可能已经有点眉目,为什么输出会是

self is <__main__.D object at 0x10ce10e48> @D.add
self is <__main__.D object at 0x10ce10e48> @B.add
self is <__main__.D object at 0x10ce10e48> @C.add
self is <__main__.D object at 0x10ce10e48> @A.add
19

了吧 ;)

下面我们来具体分析一下:

  • D 的 MRO 是: [D, B, C, A, object] 。 备注: 可以通过 D.mro() (Python 2 使用 D.__mro__ ) 来查看 D 的 MRO 信息)

  • 详细的代码分析如下:

    class A:
        def __init__(self):
            self.n = 2
    
        def add(self, m):
            # 第四步
            # 来自 D.add 中的 super
            # self == d, self.n == d.n == 5
            print('self is {0} @A.add'.format(self))
            self.n += m
            # d.n == 7
    
    
    class B(A):
        def __init__(self):
            self.n = 3
    
        def add(self, m):
            # 第二步
            # 来自 D.add 中的 super
            # self == d, self.n == d.n == 5
            print('self is {0} @B.add'.format(self))
            # 等价于 suepr(B, self).add(m)
            # self 的 MRO 是 [D, B, C, A, object]
            # 从 B 之后的 [C, A, object] 中查找 add 方法
            super().add(m)
    
            # 第六步
            # d.n = 11
            self.n += 3
            # d.n = 14
    
    class C(A):
        def __init__(self):
            self.n = 4
    
        def add(self, m):
            # 第三步
            # 来自 B.add 中的 super
            # self == d, self.n == d.n == 5
            print('self is {0} @C.add'.format(self))
            # 等价于 suepr(C, self).add(m)
            # self 的 MRO 是 [D, B, C, A, object]
            # 从 C 之后的 [A, object] 中查找 add 方法
            super().add(m)
    
            # 第五步
            # d.n = 7
            self.n += 4
            # d.n = 11
    
    
    class D(B, C):
        def __init__(self):
            self.n = 5
    
        def add(self, m):
            # 第一步
            print('self is {0} @D.add'.format(self))
            # 等价于 super(D, self).add(m)
            # self 的 MRO 是 [D, B, C, A, object]
            # 从 D 之后的 [B, C, A, object] 中查找 add 方法
            super().add(m)
    
            # 第七步
            # d.n = 14
            self.n += 5
            # self.n = 19
    
    d = D()
    d.add(2)
    print(d.n)

    调用过程图如下:

    D.mro() == [D, B, C, A, object]
    d = D()
    d.n == 5
    d.add(2)
    
    class D(B, C):          class B(A):            class C(A):             class A:
        def add(self, m):       def add(self, m):      def add(self, m):       def add(self, m):
            super().add(m)  1.--->  super().add(m) 2.--->  super().add(m)  3.--->  self.n += m
            self.n += 5   <------6. self.n += 3    <----5. self.n += 4     <----4. <--|
            (14+5=19)               (11+3=14)              (7+4=11)                (5+2=7)

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

### Python-docx 详细教程和使用方法 `Python-docx` 是一个用于创建、修改 Word 文档(`.docx` 文件)的库。它支持多种文档操作,包括但不限于段落处理、表格插入、样式设置以及图片嵌入等功能。 以下是 `Python-docx` 的一些核心功能及其具体实现方式: #### 1. 创建一个新的 Word 文档 通过导入 `Document` 类并实例化对象来创建新的 `.docx` 文件。 ```python from docx import Document document = Document() document.save("new_document.docx") # 保存新文档 ``` #### 2. 获取和编辑现有文档中的段落 可以加载现有的 `.docx` 文件,并遍历其中的段落内容进行读取或修改[^3]。 ```python from docx import Document path = "existing_file.docx" doc = Document(path) for paragraph in doc.paragraphs: print(paragraph.text) # 打印段落文本 paragraph.text = "Modified text" # 修改段落内容 doc.save("modified_file.docx") ``` #### 3. 设置段落样式 可以通过定义自定义样式或者应用内置样式来调整段落格式[^4]。 ```python from docx import Document from docx.enum.style import WD_STYLE_TYPE from docx.shared import Pt, Inches document = Document() style = document.styles.add_style('CustomStyle', WD_STYLE_TYPE.PARAGRAPH) paragraph_format = style.paragraph_format # 左侧缩进 paragraph_format.left_indent = Inches(0.5) # 首行缩进 paragraph_format.first_line_indent = Inches(-0.25) # 行距前增加空间 paragraph_format.space_before = Pt(12) p = document.add_paragraph(style='CustomStyle') p.add_run("This is a custom styled paragraph.") document.save("styled_doc.docx") ``` #### 4. 插入表格 可以在文档中添加表格,并填充数据到单元格中。 ```python from docx import Document document = Document() table = document.add_table(rows=2, cols=2) cell_1 = table.cell(0, 0) cell_1.text = "Row 1 Col 1" cell_2 = table.cell(0, 1) cell_2.text = "Row 1 Col 2" document.save("table_example.docx") ``` #### 5. 嵌入图片 支持向文档中插入本地存储的图像文件。 ```python from docx import Document from docx.shared import Inches document = Document() document.add_picture('image.png', width=Inches(1.25)) document.save("picture_example.docx") ``` #### 6. 处理复杂结构 除了基本的功能外,还可以利用该模块完成更复杂的任务,比如生成带样式的目录、管理脚注等高级特性。 --- ### 注意事项 虽然 `Python-docx` 提供了许多便捷的操作接口,但在实际开发过程中需要注意以下几点: - **兼容性问题**:某些特定版本间的差异可能导致部分功能无法正常工作,请确保安装最新稳定版。 - **性能考量**:对于大规模批量处理场景下可能效率较低,需优化算法逻辑减少不必要的重复计算开销。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值