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版)
类型提示进阶
419
形式类型参数
泛型声明中出现的类型变量。
示例:
abc.Mapping[KT, VT]
中的
KT
VT
参数化类型
使用具体类型参数声明的类型。
示例:
LottoBlower[int]
abc.Mapping[str, float]
具体类型参数
声明参数化类型时为参数提供的具体类型。
示例:
LottoBlower[int]
中的
int
下一个话题讨论如何让泛型更灵活,介绍协变、逆变和不变等概念。
15.7
 型变
如果没有在其他语言中使用泛化的经验,那么本节对你来说将是本书最难理
解的部分。型变概念抽象难懂,而且需要严谨的表述,导致本节就像数学书
中的内容一样。
其实,真正需要关注型变的基本上是代码库作者,因为只有他们才需要支持
新的泛化容器类型,或者提供基于回调的
API
。不过
,为了降低复杂度,可
以仅支持不变容器——
Python
标准库基本上就是这么做的。所以,第一遍阅
读本书时,可以跳过本节,或者只读介绍不变类型那几节。
本书首次介绍
型变
的概念是在“
Callable
类型的型变”一节,当时是将其应用于参数化泛
化的
Callable
类型。本节将扩展这个概念,涵盖泛化容器类型,利用现实中的具体事物类
比这个抽象的概念。
假设一所学校的食堂规定,只允许安装果汁自动售货机,
15
不允许安装一般的饮料自动售货
机,以防止售卖学校董事会禁止的苏打水。
16
15.7.1
 一个不变的自动售货机
下面试着为食堂的规定建模:定义一个泛化的
BeverageDispenser
类,参数化饮料的类型。
详见示例
15-18
示例
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