如何检查变量的值是否已更改 [英] How to check if a variable's value has changed
本文介绍了如何检查变量的值是否已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个变量:
var = 5
我想在变量值变化时检测并跳转到一个函数,所以如果var
不等于之前的值,我想跳转到一个函数.>
最简单的方法是什么?
另一个例子:
from datetime import datetime导入时间定义解除引用():currentMinute = datetime.now().minute检查分钟(当前分钟)def checkMinute(currentMinute):#如果 currentMinute 已更改,请执行以下操作:打印一些东西()def printSomething():打印分钟已更新"定义主():而(1):解除引用()如果 __name__ == '__main__':主要的()
解决方案
以@HelloWorld 的回答和@drIed 的评论为基础:一个不错的方法是将其包装到一个类中.
例如:
类观察者:"一个简单的类,设置为监视其变量."def __init__(self, value):self.variable = 值def set_value(self, new_value):如果 self.variable != new_value:self.pre_change()self.variable = new_valueself.post_change()def pre_change(self):pass # 在变量即将改变之前做一些事情def post_change(self):pass # 在变量改变后立即执行
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()
解决方案
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
这篇关于如何检查变量的值是否已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文