class 的 __init__ 变量改变时如何检测和触发函数

How to detect and trigger function when a class's __init__ variable is changed

我希望能够监视变量并在我的 class 中有一个函数在我的 class 的实例发生更改时被调用。

class Example:
    def __init__(self, content):
        self.content = content

example1 = Example('testing')

example1.content = 'testing123'

我希望能够检查 example1.content 是否是 changed/updated,如果它被更改,运行 一些代码。

这是您要找的吗?

class Example:
    def __init__(self, content):
        self.content = content

    def __setattr__(self, name, value):
        if name == 'content':
            if not hasattr(self, 'content'):
                print(f'constructor call with value: {value}')
            else:
                print(f'New value: {value}')
        super().__setattr__(name, value)


if __name__ == '__main__':
    example1 = Example('testing')
    example1.content = 'testing123'

输出:

constructor call with value: testing
New value: testing123

您可以像这样在 class 中使用 属性 setter:

class Example:
    def __init__(self, content):
        self.content = content

    @property
    def content(self):
        return self._content

    @content.setter
    def content(self, value):
        if hasattr(self, '_content'):
            # do function call
            print("new content! {}".format(value))

        self._content = value


x = Example('thing')


x.content = 'newthing'
new content! newthing