Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 464
Dango Avatar asked Mar 28 '26 19:03

Dango


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
like image 106
Balaji Ambresh Avatar answered Mar 31 '26 09:03

Balaji Ambresh


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
like image 26
C.Nivs Avatar answered Mar 31 '26 07:03

C.Nivs