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版)
函数中的类型提示
207
8.5.4
 泛化容器
大多数
Python
容器是异构的。例如,在一个
list
中可以混合存放不同的类型。然而,实
际使用中这么做没有什么意义。存入容器的对象往往需要进一步处理,因此至少要有一个
通用的方法。
9
泛型可以用类型参数来声明,以指定可以处理的项的类型。
例如,可以像示例
8-8
那样参数化一个
list
,约束元素的类型。
示例
8-8
带类型提示的
tokenize
函数(
Python3.9
及以上版本)
def tokenize(text: str) -> list[str]:
return text.upper().split()
Python3.9
及以上版本中,类型提示的意思是
tokenize
函数返回一个
list
,而且各项均
str
类型。
stuff: list
stuff: list[Any]
这两个注解的意思相同,都表示
stuff
是一个列表,而
且列表中的项可以是任何类型的对象。
对于
Python 3.8
或之前的版本,道理是一样的,只是需要编写的代码更多,
详见“早期支持和弃用的容器类型”附注栏。
PEP 585
Type Hinting Generics In Standard Collections
”列出了标准库中接受泛化类型提示
的容器。下面只列出了可使用最简单的泛化类型提示形式的容器,例如
container[item]
list collections.deque abc.Sequence abc.MutableSequence
set abc.Container ...
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