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版)
424
15
不可变容器可以是协变的。例如,文档中使用约定的命名方式
T_co
指明
typing.FrozenSet
有一个可协变的类型变量。
class FrozenSet(frozenset, AbstractSet[T_co]):
使用
:>
表示参数化类型,如下所示。
float :> int
frozenset[float] :> frozenset[int]
迭代器也可以是协变的。迭代器不是
frozenset
这种只读的容器,而是只产生输出。只要
预期产出浮点数的
abc.Iterator[float]
,就可以放心使用产出整数的
abc.Iterator[int]
基于同样的原因,
Callable
类型的返回值类型也可以是协变的。
3.
逆变类型
对于
A :> B
,当满足
K[A] <: K[B]
时,泛型
K
是可逆变的。
可逆变的泛型可以逆转具体类型参数的子类型关系。
TrashCan
类就是一例。
Refuse :> Biodegradable
TrashCan[Refuse] <: TrashCan[Biodegradable]
可逆变的容器通常是只写的数据结构(也叫“接收器”,
sink
)。标准库中没有这样的容器,
不过一些类型有可逆变的类型参数。
Callable[[ParamType, ...], ReturnType]
中的参数类型是可逆变的,不过
ReturnType
是可协
变的(详见“
Callable
类型的型变”一节)
。另外,
Generator
Coroutine
AsyncGenerator
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