2015-09-07 161 views
4

如果我有一個變量:如何檢查是否變量的值發生了變化

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

[在Python變量的值檢測的變化(可能重複http://stackoverflow.com/questions/7540443/detecting-change-in-the-value-of-python-變量) – asdf

+2

...你可能正在尋找一個'if'語句嗎? – nneonneo

+0

var是一個全局變量還是它屬於一個類? – Pynchia

回答

3

我會去觸發你所需功能的setter函數。

def setValue(val): 
    global globalVal 
    valueChanged= g_val != val 
    if valueChanged: 
     preFunction() 
    globalVal = val 
    if valueChanged: 
     postFunction() 
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 
相關問題