如何检查变量的值是否已更改

时间:2015-09-07 23:58:29

标签: python variables

如果我有变量:

var = 5

我希望在变量值发生变化时检测并跳转到函数,所以如果var不等于之前的值,我想跳转到函数。

最简单的方法是什么?

另一个例子:

from datetime import datetime
import time


def dereferentie():
    currentMinute = datetime.now().minute
    checkMinute(currentMinute)

def checkMinute(currentMinute):

    #if currentMinute has changed do:
        printSomething()

def printSomething():
    print "Minute is updated"


def main():
    while (1):
        dereferentie()


if __name__ == '__main__':
    main()

3 个答案:

答案 0 :(得分:3)

我会使用一个触发你所需功能的setter函数。

def setValue(val):
    global globalVal
    valueChanged= g_val != val
    if valueChanged:
        preFunction()
    globalVal = val
    if valueChanged:
        postFunction()

答案 1 :(得分:2)

以@HelloWorld的答案和@ drIed的评论为基础:一个很好的方法是将它包装成一个类。 例如:

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

答案 2 :(得分:0)

一种很好的方法是使用@property@.setter装饰器。

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

顺便说一下,这是我最喜欢的Python功能之一。

原始海报 这就是我实现您的示例的方式。

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()