0

For example, I have a class:

import datetime

class Obj:
    
    def __init__(self, attribute_1):
        self.attribute_1 = attribute_1
        self.last_edited = None

I want it to be able to do this:

# Creating object
obj1 = Obj("a") 
obj1.attribute_1 = "b"  # obj1.last_edited should have changed to datetime.datetime.now()

I'm not sure how to implement the changing of obj1's 'last_edited' attribute if I were to directly change obj1's 'attribute_1' (without any setters).

Thanks in advance.

1 Answers1

4

All Python objects have a builtin method called __setattr__ that is called whenever a field in the class is changed. This method by default updates a value in the class dictionary (stored internally to represent the state of a class instance). You can override this behavior by defining a custom __setattr__ method. For your use case, the function might look like this:

class SomeObject:
    def __init__(self, attr):
        self.attr = attr

    def __setattr__(self, name, value):
        super().__setattr__("last_edited", time.time())
        super().__setattr__(name, value)

Notice that we need to use a super call to avoid recursion (use the __setattr__ method of the base object class).

ComedicChimera
  • 466
  • 1
  • 4
  • 15