[英]How can i replace many identical conditions?
我有一個running
變量,它負責程序是否正在運行。 還有一個循環,只要running == True
就會運行。 這個循環包含許多功能,每個功能都需要 1 秒才能完成。
因此,如果在循環迭代期間將running
的值更改為False
,直到迭代完全完成,將執行操作。
對我來說,一旦running
的值變為False
,循環立即被中斷(好吧,或者幾乎是立即)。
我有這個解決方案:
running = True
while running:
do_something1(time_length=1)
if not running:
break
do_something2(time_length=1)
if not running:
break
do_something3(time_length=1)
if not running:
break
do_something4(time_length=1)
if not running:
break
do_something5(time_length=1)
if not running:
break
do_something6(time_length=1)
if not running:
break
# etc.
但是,這個選項看起來很笨拙,而且占用空間很大。 是否可以不在每個動作之前規定一個條件,而是規定它,比如說,只在開始時?
UPD 1:由於我沒有完全顯示代碼,據我所知,答案不太適合我。
所有的變量和函數都在 class 里面。代碼本身看起來是這樣的。
from threading import Thread
class SomeClass:
def __init__(self):
self.running = True
def toggle_running_flag(self):
# this function toggles self.running by user input
self.running = not self.running
if self.running:
Thread(target=self.do_all_of_this).start()
def do_something1(self):
# do something
pass
def do_something2(self):
# do something
pass
def do_something3(self):
# do something
pass
def do_all_of_this(self):
while self.running:
self.do_something1()
if not self.running:
break
self.do_something2()
if not self.running:
break
self.do_something3()
您可以使用異常來代替該標志變量。 請注意,異常不僅僅針對“壞東西”,例如StopIteration
異常是迭代器發出信號表示它們已完成的方式。
演示:
from contextlib import suppress
class StopRunning(Exception):
pass
def do_something1():
print('do_something1')
raise StopRunning
def do_something2():
print('do_something2')
with suppress(StopRunning):
while True:
do_something1()
do_something2()
print('done')
Output:
do_something1
done
各種do_something
的設置是running = False
嗎? 依賴全局不是一個好的模式。
更新全局標志的一種替代方法是讓do_somethingN
拋出異常以停止執行:
from do_things import StopRunning, do_something1, do_something2, # etc
try:
while True:
do_something1(time_length=1)
do_something2(time_length=1)
do_something3(time_length=1)
do_something4(time_length=1)
do_something5(time_length=1)
do_something6(time_length=1)
except StopRunning:
pass
別處:
# do_things.py
class StopRunning(Exception):
pass
def do_something1(time_length):
if time_length > 42:
raise StopRunning
# etc
您可以通過這種方式做到這一點。 您可以創建一個 function,它將在您必須執行的函數之間無限循環:
from itertools import cycle
class SomeClass:
def __init__(self):
self.running = True
def toggle_running_flag(self):
# this function toggles self.running by user input
self.running = True
Thread(target=self.do_all_of_this).start()
def do_all_of_this(self):
self.work = [self.do_something1, self.do_something2, self.do_something3]
for func in cycle(self.work):
func()
if not self.running:
return
每次迭代后檢查您的程序是否仍應運行。 如果不返回(停止迭代)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.