How to call a function in another object when changing a variable. python

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

  • One of the client objects changes the variable in the center of the object OR notifies the center of the change of the variable,
  • and then the central object will immediately detect the change ;
  • then, as soon as detection, the central object calls some function of the next object in the queue
  • After the client changes the variable, the client object will be deleted. The center will take care of the next client facility. Therefore, I do not assume that there is no functional chain between these objects. So this is a little different from the observer pattern. (How to solve this problem? Correct me if I am wrong.)

The following code is for demonstration purposes 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()
+4
source share
2 answers

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

You need to make the required function call in this __ setattr__(). The following is an example of an 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

, , __settattr__ .

+2

va .

class Center():
    def __init__(self):
        self.queue = None
        self._va = 0

    @property
    def va(self):
        return self._va

    @va.setter
    def va(self, value):
        self._va = value
        self.whenChanged()

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

Source: https://habr.com/ru/post/1655987/


All Articles