Add A Decorator To Existing Builtin Class Method In Python
I've got a class which contains a number of lists where whenever something is added to one of the lists, I need to trigger a change to the instance's state. I've created a simple
Solution 1:
You cannot monkey-patch builtins, so subclassing is the only way (and actually better and cleaner IMHO). I'd go for something like this:
classCustomList(list):
def__init__(self, parent_instance, *args, **kwargs):
super(CustomList, self).__init__(*args, **kwargs)
self.parent_instance = parent_instance
defappend(self, item):
self.parent_instance.added = Truesuper(CustomList, self).append(item)
classMyClass(object):
added = Falsedef__init__(self):
self.list = CustomList(self, [1,2,3])
c = MyClass()
print c.added # False
c.list.append(4)
print c.added # True
Post a Comment for "Add A Decorator To Existing Builtin Class Method In Python"