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版)
接口、协议和抽象基类
367
如果希望衍生的协议可在运行时检查,则必须再次应用这个装饰器,因为该装饰器的行
为不被继承。
21
每个协议都必须明确把
typing.Protocol
列出来,作为基类。另外,再列出要扩展的协
议。这与
Python
中的继承不是一回事。
22
现在是符合“常规”的面向对象编程方式了:只需要声明衍生协议新增的方法。
pick
方法的声明继承自
RandomPicker
本章对静态协议的定义和使用就讨论到这里了。
最后,再讲一下数值抽象基类,以及取而代之的数值协议。
13.6.8
 
numbers
模块中的抽象基类和
Numeric
协议
“论数字塔的倒下”一节讲过,标准库中
numbers
包内的抽象基类可用于做运行时类型检查。
如果想检查是不是整数,可以使用
isinstance(x, numbers.Integral)
int
bool
int
的子类),以及外部库中注册为
numbers
包中某个抽象基类的虚拟子类的整数类型,都
能通过这个测试。例如,
NumPy
供了
21
个整数类型,另外还有注册为
numbers.Real
的虚拟子类的多个浮点数类型,以及注册为
numbers.Complex
的虚拟子类的不同位宽度
bit width
)的复数。
有点儿奇怪的是,
decimal.Decimal
没有注册为
numbers.Real
的虚拟子类。原因
也很好理解,如果在程序中需要使用
Decimal
提供的精度,那么你肯定不想与
精度低的浮点数混淆。
可惜,
numbers
包定义的数字塔不是为静态类型检查设计的 ...
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