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.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin
高效能PYTHON程式設計

高效能PYTHON程式設計

Micha Gorelick, Ian Ozsvald

Publisher Resources

ISBN: 9787115612366