I want to run a function when a variable changes its value for example
I have a variable called 'v1' the default value is ZERO
Let's say I have GUI app and I press button, this button only has one function that add one to 'v1' I want another function run when it detects v1 had been change like
print('v1 change')
, run when a button click or user input or anything that can change its value , JavaScript has onchange
function dose python has something like that?
CodePudding user response:
Standard variables in Python don't have this functionality.
Some GUIs use special class(es) to keep value - and it may need to use functions to get
and set
value in class. And it has method to add functions which should be executed when variable change value. These added functions are called callbacks
Minimal working example
class Var:
def __init__(self, value=0):
self._value = value
self._callbacks = []
def set(self, value):
old_value = self._value
self._value = value
# execute functions when it set value
for func in self._callbacks:
func(old_value, value)
def get(self, value):
return self._value
def add_callback(self, func):
if func not in self._callbacks:
self._callbacks.append(func)
def remove_callback(self, func):
if func in self._callbacks:
self._callbacks.remove(func)
def myfunc(old, new):
print("changed:", old, new)
v = Var()
v.add_callback(myfunc)
v.set(10) # changed: 0 10
v.set(-10) # changed: 10 -10
v.remove_callback(myfunc)
v.set(0) # without text
CodePudding user response:
Maybe this could help you:- https://opensource.com/article/21/4/monitor-debug-python
The above website has instructions to install and use watchpoints library if that could help.