简体   繁体   English

字典成员键更改的 Python 调用函数

[英]Python call function on dictionary member key change

I have a class that looks kind of like this:我有一个看起来像这样的课程:

class MyClass:
    _properties: Dict[str, Any]

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

What I want to happen is I want to be notified when the dictionary is changed.我想要发生的是我想在字典更改时收到通知。 So when a user does this:所以当用户这样做时:

obj = MyClass()

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

I would like some callback function to be called, ideally a callback function that has access to the key and value that were created/modified.我想调用一些回调函数,理想情况下是一个可以访问创建/修改的键和值的回调函数。

The only thing I can think of is inheriting dict and overriding __setitem__ , but I am wondering if there is a nicer way to do this.我唯一能想到的是继承dict并覆盖__setitem__ ,但我想知道是否有更好的方法来做到这一点。

You can have a subclass that does what you want:你可以有一个子类来做你想做的事:

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)

output is:输出是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM