Python - 弱引用
Python 在实现垃圾回收策略时使用引用计数机制。每当内存中的一个对象被引用时,计数就会加 1。另一方面,当引用被移除时,计数减 1。如果后台运行的垃圾回收器发现某个对象的计数为 0,它就会被移除,所占用的内存也会被回收。
弱引用是一种不会保护对象免于被垃圾回收的引用。它在需要为大型对象实现缓存时非常重要,也适用于希望减少循环引用带来的麻烦的情况。
为了创建弱引用,Python 提供了一个名为 weakref 的模块。
该模块中的 ref class 管理对对象的弱引用。调用它时,会检索原始对象。
创建弱引用的方法 −
weakref.ref(class())
示例
import weakref
class Myclass:
def __del__(self):
print('(Deleting {})'.format(self)) # (删除 {})
obj = Myclass()
r = weakref.ref(obj)
print('object:', obj)
print('reference:', r)
print('call r():', r())
print('deleting obj')
del obj
print('r():', r())
在删除被引用对象后调用引用对象会返回 None。
它将产生以下输出 −
object: <__main__.Myclass object at 0x00000209D7173290> reference: <weakref at 0x00000209D7175940; to 'Myclass' at 0x00000209D7173290> call r(): <__main__.Myclass object at 0x00000209D7173290> deleting obj (Deleting <__main__.Myclass object at 0x00000209D7173290>) r(): None
回调函数
ref class 的构造函数有一个可选参数,即回调函数,当被引用对象被删除时,该函数会被调用。
import weakref
class Myclass:
def __del__(self):
print('(Deleting {})'.format(self)) # (删除 {})
def mycallback(rfr):
"""called when referenced object is deleted""" # 当被引用对象被删除时调用
print('calling ({})'.format(rfr))
obj = Myclass()
r = weakref.ref(obj, mycallback)
print('object:', obj)
print('reference:', r)
print('call r():', r())
print('deleting obj')
del obj
print('r():', r())
它将产生以下输出 −
object: <__main__.Myclass object at 0x000002A0499D3590> reference: <weakref at 0x000002A0499D59E0; to 'Myclass' at 0x000002A0499D3590> call r(): <__main__.Myclass object at 0x000002A0499D3590> deleting obj (Deleting <__main__.Myclass object at 0x000002A0499D3590>) calling (<weakref at 0x000002A0499D59E0; dead>) r(): None
终结对象
weakref 模块提供了 finalize class。其对象在垃圾回收器收集对象时被调用。该对象会存活到引用对象被调用为止。
import weakref
class Myclass:
def __del__(self):
print('(Deleting {})'.format(self)) # (删除 {})
def finalizer(*args):
print('Finalizer{!r})'.format(args)) # 终结器{!r})
obj = Myclass()
r = weakref.finalize(obj, finalizer, "Call to finalizer") # 调用终结器
print('object:', obj)
print('reference:', r)
print('call r():', r())
print('deleting obj')
del obj
print('r():', r())
它将产生以下输出 −
object: <__main__.Myclass object at 0x0000021015103590>
reference: <finalize object at 0x21014eabe80; for 'Myclass' at
0x21015103590>
Finalizer('Call to finalizer',))
call r(): None
deleting obj
(Deleting <__main__.Myclass object at 0x0000021015103590>)
r(): None
weakref 模块提供了 WeakKeyDictionary 和 WeakValueDictionary class。这些 class 不会保持映射对象中的对象存活,它们更适合用于创建多个对象的缓存。
WeakKeyDictionary
弱引用键的映射类。对键使用弱引用。当键不再有强引用时,字典中的条目将被丢弃。
WeakKeyDictionary 类的实例可以通过现有字典或无参数创建。其功能与普通字典相同,可以添加和移除映射条目。
下面的代码创建了三个 Person 实例。然后使用一个字典创建一个 WeakKeyDictionary 实例,其中键是 Person 实例,值是 Person 的姓名。
我们调用 keyrefs() 方法来获取弱引用。当对 Person1 的引用被删除后,再次打印字典键。将一个新的 Person 实例添加到具有弱引用的键的字典中。最后,再次打印字典的键。
示例
import weakref
class Person:
def __init__(self, person_id, name, age):
self.emp_id = person_id
self.name = name
self.age = age
def __repr__(self):
return "{} : {} : {}".format(self.person_id, self.name, self.age)
Person1 = Person(101, "Jeevan", 30)
Person2 = Person(102, "Ramanna", 35)
Person3 = Person(103, "Simran", 28)
weak_dict = weakref.WeakKeyDictionary({Person1: Person1.name, Person2: Person2.name, Person3: Person3.name})
print("Weak Key Dictionary : {}\n".format(weak_dict.data))
print("Dictionary Keys : {}\n".format([key().name for key in weak_dict.keyrefs()]))
del Person1
print("Dictionary Keys : {}\n".format([key().name for key in weak_dict.keyrefs()]))
Person4 = Person(104, "Partho", 32)
weak_dict.update({Person4: Person4.name})
print("Dictionary Keys : {}\n".format([key().name for key in weak_dict.keyrefs()]))
它将产生以下输出 −
Weak Key Dictionary : {<weakref at 0x7f542b6d4180; to 'Person' at 0x7f542b8bbfd0>: 'Jeevan', <weakref at 0x7f542b6d5530; to 'Person' at 0x7f542b8bbeb0>: 'Ramanna', <weakref at 0x7f542b6d55d0; to 'Person' at 0x7f542b8bb7c0>: 'Simran'}
Dictionary Keys : ['Jeevan', 'Ramanna', 'Simran']
Dictionary Keys : ['Ramanna', 'Simran']
Dictionary Keys : ['Ramanna', 'Simran', 'Partho']
WeakValueDictionary
弱引用值的映射类。当值不再有强引用时,字典中的条目将被丢弃。
我们将演示如何使用 WeakValueDictionary 创建具有弱引用值的字典。
代码类似于前一个示例,但这次我们使用 Person 姓名作为键,Person 实例作为值。我们使用 valuerefs() 方法来获取字典的弱引用值。
示例
import weakref
class Person:
def __init__(self, person_id, name, age):
self.emp_id = person_id
self.name = name
self.age = age
def __repr__(self):
return "{} : {} : {}".format(self.person_id, self.name, self.age)
Person1 = Person(101, "Jeevan", 30)
Person2 = Person(102, "Ramanna", 35)
Person3 = Person(103, "Simran", 28)
weak_dict = weakref.WeakValueDictionary({Person1.name:Person1, Person2.name:Person2, Person3.name:Person3})
print("Weak Value Dictionary : {}\n".format(weak_dict.data))
print("Dictionary Values : {}\n".format([value().name for value in weak_dict.valuerefs()]))
del Person1
print("Dictionary Values : {}\n".format([value().name for value in weak_dict.valuerefs()]))
Person4 = Person(104, "Partho", 32)
weak_dict.update({Person4.name: Person4})
print("Dictionary Values : {}\n".format([value().name for value in weak_dict.valuerefs()]))
它将产生以下输出 −
Weak Value Dictionary : {'Jeevan': <weakref at 0x7f3af9fe4180; to 'Person' at 0x7f3afa1c7fd0>, 'Ramanna': <weakref at 0x7f3af9fe5530; to 'Person' at 0x7f3afa1c7eb0>, 'Simran': <weakref at 0x7f3af9fe55d0; to 'Person' at 0x7f3afa1c77c0>}
Dictionary Values : ['Jeevan', 'Ramanna', 'Simran']
Dictionary Values : ['Ramanna', 'Simran']
Dictionary Values : ['Ramanna', 'Simran', 'Partho']