我希望能够监视变量并在类的实例发生更改时调用类中的函数。
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/