简体   繁体   中英

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. 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.

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 ?

Make a function multi_command which takes multiple commands, and executes them in order. 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".

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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