How to detect and trigger function when a class's __init__ variable is changed

Viewed 425

I want to be able to monitor the variable and have a function inside of my class be called when an instance of my class is changed.

class Example:
    def __init__(self, content):
        self.content = content

example1 = Example('testing')

example1.content = 'testing123'

I would like to be able to check if example1.content was changed/updated, and if it was changed, run some code.

2 Answers

Is this what you're looking for?

class Example:
    def __init__(self, content):
        self.content = content

    def __setattr__(self, name, value):
        if name == 'content':
            if not hasattr(self, 'content'):
                print(f'constructor call with value: {value}')
            else:
                print(f'New value: {value}')
        super().__setattr__(name, value)


if __name__ == '__main__':
    example1 = Example('testing')
    example1.content = 'testing123'

Output:

constructor call with value: testing
New value: testing123

You could use a property setter in a class like this:

class Example:
    def __init__(self, content):
        self.content = content

    @property
    def content(self):
        return self._content

    @content.setter
    def content(self, value):
        if hasattr(self, '_content'):
            # do function call
            print("new content! {}".format(value))

        self._content = value


x = Example('thing')


x.content = 'newthing'
new content! newthing
Related