Skip to Content
流畅的Python(第2版)
book

流畅的Python(第2版)

by Luciano Ramalho
April 2023
Intermediate to advanced
769 pages
25h 16m
Chinese
Posts & Telecom Press
Content preview from 流畅的Python(第2版)
继承:瑕瑜互见
379
>>> class AnswerDict2(collections.UserDict):
... def __getitem__(self, key):
... return 42
...
>>> ad = AnswerDict2(a='foo')
>>> ad['a']
42
>>> d = {}
>>> d.update(ad)
>>> d['a']
42
>>> d
{'a': 42}
为了衡量子类化内置类型所需的额外工作量,我做了一个实验,把示例
3-9
中原本继承
UserDict
StrKeyDict
类改为继承
dict
。为了让新实现通过整个测试套件,要实现
__init__
方法、
get
方法和
update
方法,因为继承
dict
的版本拒绝与覆盖的
__missing__
方法、
__contains__
方法和
__setitem__
方法合作。示例
3-9
中那个
UserDict
子类有
16
行代码,而
这个实验中的
dict
子类有
33
行代码。
5
综上所述,本节所述的问题只发生在
C
语言实现的内置类型内部的方法委托上,而且
只影响直接继承内置类型的类。如果子类化使用
Python
写的类(例如
UserDict
MutableMapping
),则不会受此影响。
6
与多重继承有关的另一个问题是,如果一个类有两个超类,而且超类中有同名属性,那么
Python
如何确定
super().attr
该使用哪个属性呢?
14.4
节将对此进行解答。
14.4
 多重继承和方法解析顺序
任何实现多重继承的语言都要处理潜在的命名冲突 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin

Publisher Resources

ISBN: 9787115612366