我目前正在构建一个小型库,并且遇到了描述符问题:我创建了一个python描述符并且它必须存储单独类的值,但我不想使用该类作为存储。而且我不希望用户必须为这些描述符继续工作。如何让python描述符知道拥有类的实例已被删除
但是,当一个对象的实例被删除时,我想删除它在该实例的描述符中的数据。 (实例可以被删除,因为描述符不包含对它的引用,所以我将它们用它们的id索引到字典中)
而且这样做是必须完成的,因为可以创建另一个实例, id,从而导致从旧对象到新对象的“数据传输”,并且这对于的任何方式都是没有帮助的。
有没有办法让描述符知道描述符所属类的一个实例已被删除?
(__delete__
只是触发如果属性被删除,而不是如果实例是越来越删除)
这里的代码一点点向您展示这是怎么一回事:
class CounterDescriptor(object): # I need the answer for something different, but the problem is the same. My code is just much larger and a whole lot more complicated.
def __init__(self) -> None:
self.counts = {}
def __get__(self, instance: object, owner: type) -> object:
instance_id = id(instance)
if instance_id not in self.counts:
self.counts[instance_id] = 0
self.counts[instance_id] += 1
return self.counts[instance_id]
def __set__(self, instance: object, value: int) -> None:
self.counts[id(instance)] = int(value)
class SomethingUsingTheCounterDescriptor(object):
x = CounterDescriptor()
x = SomethingUsingTheCounterDescriptor()
x.x # \-> count goes one higher (-> now it is 1)
del x # Now I want to get rid of the data stored for x in the CounterDescriptor.
我会只是预先感谢您,
CodenameLambda
请提供一些示例代码。我不明白::我创建了一个python描述符,它必须存储单独类的值,但我不想将该类用作存储。 PS:https://docs.python.org/3/reference/datamodel。html#实现描述符以下方法仅适用于包含方法的类的实例(所谓的描述符类)出现在所有者类中时(描述符必须位于所有者的类字典或类字典中,的父母)。 –