Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
記憶體回收
|
441
WeakValueDictionary class WeakValueDictionary(adict={})
一個
WeakValueDictionary
d
是會弱參考(weakly referencing)其
值(values)的一種映射。當
d
中的一個值
v
的參考計數降到
0
d
d[k] is v
為真的所有項目都會消失。
adict
用來初始化這種
映射。
WeakKeyDictionary
讓你非侵入性地將額外的資料關聯至一些可雜湊的物件
hashable objects),並且不變更那些物件。
WeakValueDictionary
讓你非侵
入性地記錄物件之間暫時性的關聯,並建置快取。在這些情況中,我們都
使用一個弱映射(weak mapping),而非一個
dict
,以確保可回收的物件
不會因為只是被用在一個映射中而持續存在。
一個典型的例子是會追蹤記錄其實體(instances)但不會因為這樣的追蹤
記錄而使得它們持續存在的類別:
import weakref
class Tracking(object):
_instances_dict = weakref.WeakValueDictionary()
def __init__(self):
Tracking._instances_dict[id(self)] = self
@classmethod
def instances(cls): return cls._instances_dict.values()
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

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819