【问题标题】:How to detect and trigger function when a class's __init__ variable is changed当类的 __init__ 变量更改时如何检测和触发函数
【发布时间】:2020-10-27 01:03:14
【问题描述】:

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

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

example1 = Example('testing')

example1.content = 'testing123'

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

【问题讨论】:

标签: python class observer-pattern


【解决方案1】:

这是你要找的吗?

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

【讨论】:

  • 有没有办法让它在第一个实例被创建并且只有在实例被“编辑”之后才运行?
  • 拦截每一次分配给属性的尝试以捕获分配给其中一个的分配是相当严厉的。正如property 类所实现的那样,描述符协议已经提供了一种方法来检测您要拦截的分配。
  • 在此解决方案中,您可以检查调用函数并在需要时打印“更改”。您可以查看this 的答案以获取调用者函数名称
  • 这是一个很好的答案.. 很有帮助,我学到了一些东西
【解决方案2】:

您可以在这样的类中使用属​​性设置器:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2022-08-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    相关资源
    最近更新 更多