Is there some general way to get a class to run a function when any of its attributes are modified? I wondered if some subprocess could be running to monitor changes to the class, but maybe there's a way to inherit from class
and modify some on_change
function that is a part of the Python class, a bit like how the default __repr__
method of a class can be modified. What would be some sensible approach here?
The actual application is not to just do a printout but to update entries in a database that correspond to data attributes of instantiated classes.
#!/usr/bin/env python
class Event(object):
def __init__(self):
self.a = [10, 20, 30]
self.b = 15
#def _on_attribute_change(self):
# print(f'attribute \'{name_of_last_attribute_that_was_changed}\' changed')
event = Event()
event.a[1] = 25
# printout should happen here: attribute 'a' changed
event.a.append(35)
# printout should happen here: attribute 'a' changed
event.c = 'test'
# printout should happen here: attribute 'c' changed