如何将未知参数应用于 Python 3.x 中的函数? [英] How do I apply unknown arguments to a function in Python 3.x?

查看:32
本文介绍了如何将未知参数应用于 Python 3.x 中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的引擎开发自己的 GUI,并且我已经创建了一个对象"称为 EwConsole(一个简单的下拉"控制台来输入命令).为了做到这一点,我只是在字典中存储了一个要通过输入/返回触发"的函数的 ID,作为函数对象本身的键.我的问题是参数和 Python 3.x.

I'm developing my own GUI for my engine, and I've created an "object" called EwConsole (A simple "drop-down" console to input commands). In order to do that, I simply store an ID for the function to be "triggered with enter/return" as the key to the function-object itself in a dict. My problem is with the arguments, and Python 3.x.

这是我创建新控制台命令"的方法:

Here's my method for creating a new "console command":

def create_command(self, command_id, command_function):
    self["commands"][command_id] = command_function

我开发了自己的输入对象,称为EwInput",它有一个方法可以返回已写入其中的字符串值.为了分隔存储命令的参数,我拆分了字符串的空格.这是在控制台中监视"命令"的代码:

I've developed my own input object, called "EwInput", which has a method that returns the string value that has been written in it. In order to separate the arguments of the stored command, I split the spaces of the string. Here's the code that "watches" for "commands" in the console:

def watch_for_commands(self):
    if push_enter():
        values = self["input"].get_value().split()
        if values[0] in self["commands"]:
            if len(values) == 1:
                self["commands"][values[0]]()
            elif len(values) > 1:
                try:
                    self["commands"][values[0]](values[1:]) # Problem here.
                except TypeError:
                    raise ErgameError("The given function '{0}' does not support the given arguments: {1}.".format(values[0], values[1:]))
        else:
            print("There is no such command: {}".format(values[0]))

如您所见,由于命令创建"是完全通用的,因此不可能知道给定函数将具有多少个参数.正如这里所见,在旧的 2.x 中,它是可以将apply"与参数列表一起使用.

As you can see, since the "command creation" is completely generic, it's not possible to know how many arguments the given function will have. As one can see here, in the old 2.x, it was possible to use "apply" with a list of arguments.

问题来了:

在 Python 3.x 中,如果强制我使用__ call __",我如何将未知数量的参数应用"到函数中???Python 3.x 中有没有办法将任意序列的参数应用于未知函数?

How, in Python 3.x, can I "apply" an unknown number of arguments to a function, if it is forcing me to use "__ call __"??? Is there a way in Python 3.x to apply an arbitrary SEQUENCE of arguments to an unknown function?

推荐答案

尝试使用 参数解包.

self["commands"][values[0]](*values[1:])

这篇关于如何将未知参数应用于 Python 3.x 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆