如何在类的 __init__ 变量更改时检测和触发功能

Dan*_*ngo 2 python class observer-pattern

我希望能够监视变量并在更改类的实例时调用类中的函数。

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

example1 = Example('testing')

example1.content = 'testing123'
Run Code Online (Sandbox Code Playgroud)

我希望能够检查是否example1.content已更改/更新,如果已更改,请运行一些代码。

Bal*_*esh 5

这是你要找的吗?

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'
Run Code Online (Sandbox Code Playgroud)

输出:

constructor call with value: testing
New value: testing123
Run Code Online (Sandbox Code Playgroud)