Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - How to check if a variable's value has changed

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 equal to the value it was before, I want to jump to a function.

What is the easiest way to do this?

Another example:

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.variable != new_value:
            self.pre_change()
            self.variable = new_value
            self.post_change()
    
    def pre_change(self):
        pass # do stuff before variable is about to be changed
        
    def post_change(self):
        pass # do stuff right after variable has changed
        

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...