gpt4 book ai didi

Python One-Shot,水平触发,边缘触发

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:39 27 4
gpt4 key购买 nike

我正在监控 python-twisted 框架中的 bool 值。当 bool 值改变时,我只想执行一次函数。这可以用 Python 完成吗?

我正在从 IO 设备中串行提取 bool 值。在某个时间间隔轮询该值。当值改变时我想执行一个函数。

最佳答案

用类比用全局变量更好。

class EdgeTrigger(object):
def __init__(self, callback):
self.value = None
self.callback = callback

def __call__(self, value):
if value != self.value:
self.callback(self.value, value)
self.value = value

要使用此代码,请创建一个包含应调用函数的对象:

def my_callback(oldVal, newVal):
print "Value changed from {0} to {1}.".format(oldVal, newVal)

detector = EdgeTrigger(my_callback)

然后在获得每个新值时“调用”该对象:

with open("infile.txt") as f:
for line in f:
detector(line.strip())

这将从文件中读取行并在两个连续行不相同时打印一条消息。

$ cat infile.txt 
1
1
1
2
2
1

1
2
2
5
$ python edgedetect.py
Value changed from None to 1.
Value changed from 1 to 2.
Value changed from 2 to 1.
Value changed from 1 to .
Value changed from to 1.
Value changed from 1 to 2.
Value changed from 2 to 5.

关于Python One-Shot,水平触发,边缘触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23372983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com