How to check if a variable's value has changed

后端 未结 3 1442
南笙
南笙 2020-12-18 05:04

If I have a variable:

var = 5

I want to detect and jump to a function when the value of the variable changes, so if var is not

3条回答
  •  無奈伤痛
    2020-12-18 05:22

    Building on @HelloWorld's answer and @drIed's comment: A nice way would be, to wrap this into a class. For example:

    class Watcher:
        """ A simple class, set to watch its variable. """
        def __init__(self, value):
            self.variable = value
    
        def set_value(self, new_value):
            if self.value != new_value:
                self.pre_change()
                self.variable = new_value
                self.post_change()
    
        def pre_change(self):
            # do stuff before variable is about to be changed
    
        def post_change(self):
            # do stuff right after variable has changed
    

提交回复
热议问题