[英]How do I apply unknown arguments to a function in 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). 我正在为引擎开发自己的GUI,并且创建了一个名为EwConsole的“对象”(一个简单的“下拉”控制台,用于输入命令)。 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.
为了做到这一点,我只存储要“通过输入/返回触发”的函数的ID作为字典中函数对象本身的键。 My problem is with the arguments, and Python 3.x.
我的问题是参数和Python3.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
I've developed my own input object, called "EwInput", which has a method that returns the string value that has been written in it. 我已经开发了自己的输入对象,称为“ EwInput”,它具有一种返回已写入其中的字符串值的方法。 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]))
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.
就像在这里看到的那样 ,在旧的2.x版本中,可以将“ apply”与参数列表一起使用。
Now comes the question: 现在出现问题:
How, in Python 3.x, can I "apply" an unknown number of arguments to a function, if it is forcing me to use "__ call __"??? 如果它迫使我使用“ __ call __”,如何在Python 3.x中将未知数量的参数“应用于”函数? Is there a way in Python 3.x to apply an arbitrary SEQUENCE of arguments to an unknown function?
在Python 3.x中,有没有一种方法可以将参数的任意SEQUENCE应用于未知函数?
尝试使用参数拆包 。
self["commands"][values[0]](*values[1:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.