python - 当类的 __init__ 变量更改时如何检测和触发函数

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

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'

输出:

constructor call with value: testing
New value: testing123

https://stackoverflow.com/questions/62763958/

相关文章:

javascript - 如何使用 react 模态显示没有背景效果的模态?

php - 试图从 laravel 中 Eloquent 产品评论中获取评论者的姓名

amazon-web-services - terraform 可以复制 s3 存储桶的内容吗?

python - 合并具有两个公共(public)值的行 | Python

c# - 在 C# 中的 SQL CLR 函数中设置小数精度

r - 使用 R Shiny 中的操作按钮将行从一个 DT 移动到其他 DT

ios - Flutter NSException : Configuration fails. 可

r - 在 R 中将日期偏移一个月

javascript - 如何使用 typescript 导出 Mongoose 模式?

pdf - 从 S3 读取 pdf 对象