gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:09:01 24 4
gpt4 key购买 nike

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

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

关于python - 当类的 __init__ 变量更改时如何检测和触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62763958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com