Skip to content
Advertisement

how to trigger function in another object when variable changed. Python

As far as I know, this is like an Observer pattern. Scenario: A Center object keeps a list (queue) of all its clients. I’m using Twisted.

  1. One of client objects changes a variable in center object OR notify the center to change the variable,
  2. and then the center object detects the change immediately;
  3. then as soon as the detection, the center object invoke some function of next object in queue
  4. After the client changed the variable, the client object will be eliminated. The center will take care of next client object. So I imagine there’s no any function chain between these objects. So it’s a little bit different from observer pattern. (How to address this issue? Correct me if I’m wrong.)

following code is just for demo only:

    class client():
        def change(self):
            self.center.va = 1

        def inqueue(self):
            self.center.queue.enqueue(self)

        def function(self):
            pass

    class center():
        def __init__(self):
            self.queue = None
            self.va = 0

        ####  When the self.va changes, this func will be invoked
        def whenChanged(self):
            next = self.queue.dequeue()
            next.function()

Advertisement

Answer

Whenever a property of class is changed, setattr() function is called. You can override this by defining __setattr__(self, property, value) function in your class.

You need to make your required function call within this __ setattr__(). Below is the sample example based on your requirement:

class Centre(object):
    def __init__(self):
        self.queue = None
        self.va = 0

    def whenChanged(self):
        next = self.queue.dequeue()
        next.function()

    def __setattr__(self, key, value):
        self.key = value
        self.whenChanged()  # <-- Your function

Whenever you will attempt to change the value of any of class’s property, this __settattr__ function will be called.

Advertisement