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版)
656
22
示例
22-16
__init__
中定义存储数据的属性,利用键共享优化措施
class Event(Record):
def __init__(self, **kwargs):
self.__speaker_objs = None
super().__init__(**kwargs)
# 省略15...
@property
def speakers(self):
if self.__speaker_objs is None:
spkr_serials = self.__dict__['speakers']
fetch = self.__class__.fetch
self.__speaker_objs = [fetch(f'speaker.{key}')
for key in spkr_serials]
return self.__speaker_objs
示例
22-15
和示例
22-16
用到的缓存技术在遗留的
Python
基准代码中十分常见。然而,
在多线程程序中,像这样自己实现的缓存容易引入竞争条件,导致数据损坏。如果两个线
程同时读取一个尚未缓存的特性,那么第一个线程需要把计算得到的数据存入缓存属性
(本例中的
__speaker_objs
)名下,当第二个线程从缓存中读取数据时,计算过程可能还
未结束。
幸好,
Python 3.8
引入了对线程安全的
@functools.cached_property
装饰器。然而,使用这
个装饰器时有一些注意事项, ...
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