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 ChangingCla
Solution 1:
You'd have to add a __setattr__()
method:
defChangeMonitor(cls):
_sentinel = object()
old_setattr = getattr(cls, '__setattr__', None)
def__setattr__(self, name, value):
old = getattr(self, name, _sentinel)
if old notis _sentinel and old != value:
print"Old {0} = {1!r}, new {0} = {2!r}".format(name, old, value)
if old_setattr:
old_setattr(self, name, value)
else:
# Old-style class
self.__dict__[name] = value
cls.__setattr__ = __setattr__
return cls
This should handle existing __setattr__
hooks as well. The _sentinel
is used to allow None
as the old value too.
Demo:
>>>changer = ChangingClass(5)>>>changer.x = 6
Old x = 5, new x = 6
>>>changer.x = 6>>># nothing printed...>>>changer.x = None
Old x = 6, new x = None
>>>changer.x = 6
Old x = None, new x = 6
Post a Comment for "Decorating A Class To Monitor Attribute Changes"