Sunday, 15 September 2013

Decorating a class to monitor attribute changes

Decorating a class to monitor attribute changes

I want to have classes that automatically send notifications to
subscribers whenever one of their attributes change. So if I would write
this code:
@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")
The output would be:
Going to change x
Old x = 5, new x = 6
Going to not change x.
End of program.
My question is how to implement the ChangeMonitor decorator class. In the
above example I assume it will print a line indicating the changes of an
attribute, but for useful purposes it could send notifications to
subscribed objects.

No comments:

Post a Comment