[英]How can I increment a variable inside a function without using global variable please?
我需要一種每秒打印一個計時器並每 10 秒執行一次操作的方法。 該程序的 output 應該如下所示。
計時器為 1
計時器為 2
定時器是 3
定時器是 4
定時器是 5
定時器是 6
定時器是 7
定時器是 8
定時器是 9
定時器是 10
動作被執行
計時器為 1
計時器為 2
定時器是 3
定時器是 4
定時器是 5
定時器是 6
定時器是 7
定時器是 8
定時器是 9
定時器是 10
動作被執行
計時器為 1
計時器為 2
定時器是 3
. . .
該程序應使用線程。 它不應該是無限的 while 循環。
我本可以用下面的代碼完成它,但它使用了一個全局變量。 如果不使用全局變量並使用如下所示的少量代碼,我該怎么做。
import threading
import time
global MytTimer
MytTimer=0
def foo():
global MytTimer
MytTimer=MytTimer+1
print("Timer is " + str(MytTimer))
threading.Timer(1, foo).start()
if MytTimer >= 10:
MytTimer=0
print("Action is executed")
foo()
我通過創建一個 class 來做到這一點。
import threading
import time
class count():
def __init__(self, MytTimer):
self.MytTimer = MytTimer
self._run()
def _run(self):
threading.Timer(1, self._run).start()
self.MytTimer += 1
print("Timer is " + str(self.MytTimer))
if self.MytTimer >= 10:
self.MytTimer=0
print("Action is executed")
a=count(MytTimer = 0)
您可以創建一個代碼線程,將值 1-10 傳遞到隊列,然后創建一個消費者,只要從隊列中讀取的值為10
,它就會執行一個操作:
import threading
import time
import queue
def foo():
q = queue.Queue()
def ticker():
while True:
for i in range(1,11):
print(f'Timer is {i}')
q.put(i)
time.sleep(1)
t_ticker = threading.Thread(target=ticker)
t_ticker.start()
while True:
i = q.get()
if i == 10:
print("Action is executed")
foo()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.