【问题标题】:Python call function on dictionary member key change字典成员键更改的Python调用函数
【发布时间】:2021-10-02 05:02:45
【问题描述】:

我有一个看起来像这样的类:

class MyClass:
    _properties: Dict[str, Any]

    @property
    def properties(self) -> Dict[str, Any]:
        ...

我希望在字典更改时收到通知。所以当用户这样做时:

obj = MyClass()

obj.properties['optimization'] = '-O3'

我想调用一些回调函数,理想情况下是一个回调函数,它可以访问创建/修改的键和值。

我唯一能想到的就是继承dict 并覆盖__setitem__,但我想知道是否有更好的方法来做到这一点。

【问题讨论】:

  • IMO 继承 dictNotifierDict 是一种干净的方法。你到底不喜欢这个主意的什么地方?
  • 如果你不想继承dict,你可以选择继承collections.UserDict

标签: python observer-pattern


【解决方案1】:

你可以有一个子类来做你想做的事:

class MyClass:
    class Properties(dict):
        def __setitem__(self, key, value):
            print("Key {} was set to {}".format(key, value))
            super().__setitem__(key, value)

    _properties = Properties()

    @property
    def properties(self) -> Dict[str, Any]:
        return self._properties


m = MyClass()
m.properties['a'] = 12
print(m.properties)

输出是:

Key a was set to 12
{'a': 12}

【讨论】:

    猜你喜欢
    • 2022-07-12
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 2016-12-22
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多