gpt4 book ai didi

python - 如果变量的值在 python 中发生变化,如何打印语句?

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

假设我的代码是这样的:

while True:
nheight = tc.getblockcount()['count']

tc.getblockcount... 是一个 rpc 调用,结果是一个存储在变量 nheight 中的整数。这个值变化 30 秒左右,那么如何让它在变化时打印一条语句呢?现在我做了这样的事情:

height = tc.getblockcount()['count']

while True:

nheight = tc.getblockcount()['count']

if height != nheight:

print("Val Changed")

height = nheight

time.sleep(0.4)

因此希望当 nheight 发生变化时,它会检测到它,因为它不同于具有原始相同值的 height。然后它更新值 height 以便它不会继续打印 Val Changed 因为值改变了一次。然后休眠0.4秒再循环

现在的问题是它打印一次“Val Changed”但不会再打印一次,即使值发生变化(我已经通过插入一些打印语句验证了这一点)

有人可以帮我制作一些东西,当 nheight 的值发生变化时会打印一些东西吗?

另外,如果可能的话,由于我的其余代码不是使用 OOP 编写的,而且我不太了解它,因此在没有 OOP 的情况下给出示例?

(我认为有一种叫做观察者模式的东西,对吗?)

非常感谢!!

最佳答案

因为我不知道 tc.getblockcount 是什么,所以这里是一个返回大部分相同数字但有 10% 的时间会更改的函数

def value_iter():
last_value = 1
while True:
yield last_value
if random.random() < 0.1:
last_value = last_value + 1

def getblockcount(it=value_iter()):
return next(it)

height = getblockcount()
while True:
nheight = getblockcount()
print(nheight,"=?=",height)
if nheight != height:
print("UPDATE!\n\n")
height=nheight

如您所见,如果您复制它,它会按预期工作

关于python - 如果变量的值在 python 中发生变化,如何打印语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51014427/

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