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版)
532
18
LBYL
三思而后行(
Look
before you leap
)。这种编程风格在调用函数或查找属性或键之前
显式测试前提条件。与
EAFP
风格相比
,这种风格的特点是代码中有很多
if
语句。
在多线程环境中,
LBYL
风格可能会在
“检查”和“行事”的空隙引入条件竞争。
例如,对
if key in mapping: return mapping[key]
这段代码来说,如果在测试之
后——但在查找之前——另一个线程从映射中删除了那个键,那么这段代码就会失
败。这个问题可以使用锁或者
EAFP
风格解决。
如果选择使用
EAFP
风格,那就要更深入地了解
else
子句,并在
try
/
except
语句中合理使用。
讨论
match
语句时,有些人(包括我)认为
match
语句也应该有一个
else
句。最后的决定是不需要这个子句,因为
case _:
具有同样的作用。
13
下面对本章做个小结。
18.5
 本章小结
本章首先讨论了上下文管理器和
with
语句的作用。很快我们就知道,除了自动关闭打开
的文件之外,
with
语句还有很多用途。我们自己动手实现了一个上下文管理器——定义了
__enter__
/
__exit__
方法的
LookingGlass
类,说明了如何在
__exit__
方法中处理异常。
Raymond Hettinger
PyCon US 2013
上所做的主题演讲传达了一个重要的观点
with
不仅
能管理资源,还可用于去掉常规的设置和清理代码,或者在另一个过程前后执行的操作。
14
随后,我们分析了标准库中
contextlib ...
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