繁体   English   中英

当一个类的__init__变量改变时如何检测和触发function

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

我希望能够监视变量并在我的 class 内部有一个 function 在我的 class 的实例被更改时被调用。

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

example1 = Example('testing')

example1.content = 'testing123'

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

这是你要找的吗?

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'

Output:

constructor call with value: testing
New value: testing123

您可以像这样在 class 中使用属性设置器:

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

暂无
暂无

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

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