【发布时间】:2013-09-19 16:15:47
【问题描述】:
我希望类能够在订阅者的某个属性发生变化时自动向订阅者发送通知。所以如果我要写这段代码:
@ChangeMonitor
class ChangingClass(object):
def __init__(self, x):
self.x = x
changer = ChangingClass(5)
print("Going to change x.")
changer.x = 6
print("Going to not change x.")
changer.x = 6
print("End of program")
输出将是:
Going to change x
Old x = 5, new x = 6
Going to not change x.
End of program.
我的问题是如何实现 ChangeMonitor 装饰器类。在上面的示例中,我假设它会打印一行指示属性的更改,但出于有用的目的,它可以向订阅的对象发送通知。
【问题讨论】:
标签: python decorator python-decorators