简体   繁体   English

调用函数的Python重复函数

[英]Python repeat function that calls functions

I have a program where the user should be able to pick and choose commands from a drop down list. 我有一个程序,用户应该可以从下拉列表中选择命令。 In this list, there is also a repeat command, which does basically what a for loop does, so all the commands in between repeat and end repeat should be looped the number of times stated. 在此列表中,还有一个repeat命令,该命令基本上执行for循环的操作,因此,在repeatend repeat之间的所有命令都应循环执行指定的次数。 See picture: 看图片:

在此处输入图片说明

Now, I don't yet know how to programatically handle the repeat-functions. 现在,我还不知道如何以编程方式处理重复功能。 I know that python handles classes like objects, so maybe that can help, but I'm a bit lost. 我知道python处理对象之类的类,所以也许可以帮上忙,但是我有点迷路了。

At the moment I send a list of strings to the thread that handles execution of the commands, and that is parsed and each command is executed. 此刻,我向处理命令执行的线程发送了一个字符串列表,该字符串被解析并执行了每个命令。

def command(self, item):
    if item.startswith('Pan'):
        ... do stuff
    elif item.startswith('...'):
        ... do something else

How would I rewrite this so that repeat is a callable function/method ? 我将如何重写此代码,以便repeat是可调用的函数/方法?

Make a function multi_command which takes multiple commands, and executes them in order. 使一个函数multi_command接受多个命令,并按顺序执行它们。 When this function encounters a "repeat", create a list of all the following commands up until you get the corresponding "end repeat". 当此功能遇到“重复”时,请创建以下所有命令的列表,直到获得相应的“结束重复”为止。 This new list is then a sub-set of your total list. 然后,此新列表是您的总列表的子集。 Call multi_command with this list, and afterwards, skip to the command that comes after the "end repeat". 使用此列表调用multi_command ,然后跳至“结束重复”之后的命令。

Psuedo-code: 伪代码:

def multi_commands(items):
    highest_idx_already_done = 0
    for idx, item in enumerate(items):
        if highest_idx_already_done > idx:
            continue
        if item == "repeat":
            num_repeats = ...
            sub_items = []
            for sub_item in items[idx+1:]:
                if sub_item == "end repeat":
                   break
                sub_items.append(sub_item[5:]) # Skip indentation
            highest_idx_already_done = idx + len(sub_items)
            for _ in range(num_repeats):
                multi_commands(sub_items)
        else:
            command(item)

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

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