在 Python 中更新可变项时自动执行操作

Auto-perform actions when updating a mutable in Python

我知道如何使用 属性 设置器在每次修改 class 的属性时执行操作,以避免每次更改变量时都必须在每个操作中编写代码。

我想知道是否可以对列表和字典等可变对象执行相同的操作?

我要实现的是以下,

我有字典d = {string : object}

with object class 的一个实例,它有一个名为 x.

的属性

当我向我的字典中添加一个新的 string:object 对时,对象的属性 x!= 0,然后我还将 object 添加到名为 x_instances.

的列表

您必须使用自定义 class;你可以 subclass dictcollections.UserDict(), and override the appropriate container special methods 来检测变化。

例如,object[subscription] = value 被翻译成 object.__setitem__(subscription, value),让您检查 value 并据此采取行动:

class MutationDictionary(dict):
    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        if isinstance(value, SomeClass) and value.x != 0:
            x_instances.append(value)

请查看 other methods that dict objects implement;例如,您可能也想覆盖 dict.setdefault()