简体   繁体   English

我如何替换许多相同的条件?

[英]How can i replace many identical conditions?

I have a running variable which is responsible for whether the program is running or not.我有一个running变量,它负责程序是否正在运行。 There is also a loop that runs as long as running == True .还有一个循环,只要running == True就会运行。 This loop contains many functions, each of which takes, say, 1 second to complete.这个循环包含许多功能,每个功能都需要 1 秒才能完成。

Thus, if during the iteration of the loop the value of running is changed to False until the iteration is completely completed, the actions will be performed.因此,如果在循环迭代期间将running的值更改为False ,直到迭代完全完成,将执行操作。

It is necessary for me that as soon as the value of running becomes False , the cycle is interrupted immediately (well, or almost immediately).对我来说,一旦running的值变为False ,循环立即被中断(好吧,或者几乎是立即)。

I have this solution:我有这个解决方案:

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.

However, this option looks very clumsy and takes up a lot of space.但是,这个选项看起来很笨拙,而且占用空间很大。 Is it possible not to prescribe a condition before each action, but to prescribe it, say, only at the beginning?是否可以不在每个动作之前规定一个条件,而是规定它,比如说,只在开始时?

UPD 1: Due to the fact that I did not fully show the code, the answers do not quite suit me, as I understand it. UPD 1:由于我没有完全显示代码,据我所知,答案不太适合我。

All variables and functions are inside the class. The code itself looks like this.所有的变量和函数都在 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()
        

Instead of that flag variable, you could use an exception.您可以使用异常来代替该标志变量。 Note that exceptions aren't just for "bad stuff", for example the StopIteration exception is how iterators signal that they're done.请注意,异常不仅仅针对“坏东西”,例如StopIteration异常是迭代器发出信号表示它们已完成的方式。

Demo:演示:

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: Output:

do_something1
done

Try it online! 在线试用!

Are the various do_something s setting running = False ?各种do_something的设置是running = False吗? Relying on globals isn't a great pattern.依赖全局不是一个好的模式。

One alternative to updating a global flag is to have do_somethingN throw an exception to stop execution:更新全局标志的一种替代方法是让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

Elsewhere:别处:

# do_things.py
class StopRunning(Exception):
    pass

def do_something1(time_length):
    if time_length > 42:
        raise StopRunning

# etc

The is a way you can do that.您可以通过这种方式做到这一点。 You can create a function that will loop indefinitely between the functions you have to execute:您可以创建一个 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

After every iteration check if your program should still be running.每次迭代后检查您的程序是否仍应运行。 If not return (Stop iteration)如果不返回(停止迭代)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM