【问题标题】:How to efficiently detect the change of a variable in Python 3?如何有效地检测 Python 3 中变量的变化?
【发布时间】:2019-07-08 17:07:38
【问题描述】:

我想知道如何有效地检查变量的值是否发生了变化,如果发生了变化,则返回该值。目前我有这样的事情:

while(True):
    if paramCHK == x:
        // do this
    elif paramCHK == y:
        // do that
        // and that
        // and that

上面实现的问题是,当我在elif子句中,参数变为x时,由于子句的执行时间太长,没有检测到。

我的想法是创建一个线程并以并行方式不断监视参数,当检测到更改时,将其报告给主函数:

myThread():
    if paramCHK.changed():
        notify_main() 

main():
   when notification:
       getParamValue()
       // do something depending the value

你会如何在 python 中解决这个问题?提前致谢

【问题讨论】:

标签: python-3.x multithreading polling


【解决方案1】:
pastx=x
while True:
    if x != pastx:
        pastx=x
        alert()    
    pastx=x

这段代码可以在你的while循环开始,并且会检测x在最后一个循环中是否发生了变化,如果有,就会运行alert()函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-20
    • 2011-11-24
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多