How to check if a variable's value has changed

后端 未结 3 1445
南笙
南笙 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

    A great way is to use the @property and @.setter decorators.

    class MyClass:
        @property
        def property_name(self):
            return self.some_value
    
        @property_name.setter
        def property_name(self, new_value):
           self.some_value = new_value
    
    obj = MyClass()
    obj.property_name = "New Value"
    stored_value = obj.property_name
    

    By the way this is one of my favorite features in Python.

    Original Poster Here's how I would implement your example.

    from datetime import datetime
    
    class TimeManager:
        # The actual variable holding data
        # You don't need to declare it, but I like to
        _current_minute = None
    
        @property
        def current_minute(self):
            """Retrieve the local variable value."""
            return self._current_minute
        @current_minute.setter
    
        @current_minute.setter
        def current_minute(self, value):
            """Same method name, but set the local variable."""
            self._current_minute = value
            print("Minute has updated to {}".format(self._current_minute))
    
        @current_minute.deleter
        def current_minute(self):
            """You can also delete variables."""
            del self._current_minute
    
    
    def main():
        # Create the class
        time_manager = TimeManager()
        for i in range(100):
            current_minute = datetime.now().second
            # set the .currrent_minute using a @property
            time_manager.current_minute = current_minute
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题