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.
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()
How to use a variable from another function in Python: The variable can be assigned to the function object inside the function body. So the variable exists only after the function has been called. Once the function has been called, the variable will be associated with the function object.
The variable can be assigned to the function object inside the function body. So the variable exists only after the function has been called. Once the function has been called, the variable will be associated with the function object. This variable can now be used anywhere inside or outside any function.
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__ ().
The variable can be assigned to the function object inside the function body. So the variable exists only after the function has been called. Once the function has been called, the variable will be associated with the function object.
Make va
a property.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With