Skip to Content
Python入门指南, 3rd Edition
book

Python入门指南, 3rd Edition

by Bill Lubanovic
September 2025
Intermediate to advanced
660 pages
7h 15m
Chinese
O'Reilly Media, Inc.
Content preview from Python入门指南, 3rd Edition

第 14 章 类型提示和文档 类型提示和文档

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

一个人永远也不可能创造出像他所暗示的那样可怕和令人印象深刻的东西

H.P. 洛夫克拉夫特

Python 在设计之初,变量实际上只是对对象的引用:名称或便签,附在包含所有细节的数据上。 因此,多年来,几乎不需要说明变量所指的数据类型。 但有时,我们这些不完美的人类会拼错名称,或忘记我们在长代码块中要做什么。 因此,最终在语言中加入了可选的类型提示。 您可以使用这些提示来表明您的意思。 Python 解释器不会强制执行类型提示,但它可以作为文档,像 Mypy 这样的工具可以理解它们,并使用它们进行错误检查。

类型提示

静态 语言要求您定义变量的类型,它们可以在编译时捕捉到一些错误。众所周知,Python 并不这样做,您可能只有在运行代码时才会发现 bug。对象有严格的类型和在内存中的位置,但变量只是一个名称,可以在任何时候指向任何对象。

然而,在实际代码中 (Python 和其它语言),一个名称往往指向一个特定的对象。 如果我们能在代码元素 (变量、函数返回等) 上注释我们期望它们引用的对象类型,那么至少在文档中是有帮助的。 这样开发人员就不需要翻阅那么多代码来了解特定变量应该如何操作了。

Python 3.5 增加了类型提示(或类型注释)来解决这个问题。 它们的使用完全是可选的,不会强制变量的类型。 类型提示可以帮助那些习惯于静态语言的开发者,在静态语言中,变量类型必须声明(或可以通过某种方式推断)。 这些只是提示,它们不会改变 Python 的工作方式。 它们的主要用途是文档,但人们也发现了更多的用途。 例如,FastAPI Web 框架使用提示来生成 Web 文档和用于测试的实时表单。

您可以对变量、函数、对象属性和方法应用类型提示。

变量提示

变量类型提示可以只指定类型:

  • name : type

或类型和一个值:

  • name : type = value

类型可以是标准的 Python 类型名,如intstr

palindrome: str = "Was it a car or a cat I saw?"

对于 list、tuple 和 dict 等集合类型,可以指定集合中的类型:

  • name: dict[keytype, valtype] = {key1: val1, key2: val2}
>>> nays: dict[str, str] = {
... "horse": "neigh",
... "pedant": "nay!",
... "genealogist": "n\N{LATIN SMALL LETTER E WITH ACUTE}e"
... }
>>>

如果变量真的可以是任何类型(这并不常见),从typing 导入Any并使用它:

  • mysterious_thing: Any

如果变量可以是多种类型中的一种,在 Python 3.10 及以上版本中可以这样说:

  • number: int | float

在 Python 的早期版本中,您需要从typing 模块中导入Union

>>> from typing import Union
>>> number: Union(int, float)

如果变量可能有类型和值,但也可能缺失,请使用None (Python 3.10+) 或Optional

>>> from typing ...
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

生成式人工智能设计模式

生成式人工智能设计模式

Valliappa Lakshmanan, Hannes Hapke

Publisher Resources

ISBN: 9798341668898