[英]Python - passing a function as an argument to another function
I have two files; 我有两个文件;
The first file, myProgram.py
, is a python file with a number of functions 第一个文件
myProgram.py
是具有许多功能的python文件
one of the functions contained inside is myFunction
this function would be called with 其中包含的函数之一是
myFunction
该函数将与
import myProgram myProgram.thisFunction() myProgram.thatFunction()
The second file contains a menu system, with calls to the functions in myProgram.py
第二个文件包含一个菜单系统,其中包含对
myProgram.py
的函数的myProgram.py
I'd like to call a particular function based on an argument passed to a function in file2 我想根据传递给file2中函数的参数来调用特定函数
def file2_function(function):
myProgram.function
file2_function(thisFunction(x,y,z))
which would essentially create myProgram.thisfunction(x,y,z) and execute it. 这实际上将创建myProgram.thisfunction(x,y,z)并执行它。
I guess I could do this using a bunch of if/elif statements, say: 我想我可以使用一堆if / elif语句来做到这一点,例如:
def file2_function(function):
if function == 1:
myProgram.thisFunction
elif function == 2:
myProgram.thatFunction
Though that could get messy as I'm already using a lot of if/elif/else statements for the menu system. 虽然那样可能会很麻烦,因为我已经在菜单系统中使用了很多if / elif / else语句。
Is there a better way (or is the if/elif route the way to go?) 有没有更好的方法(或者if / elif路线是走的路?)
You can create a dictionary where key is the name of the function, and value is the function itself. 您可以创建一个字典,其中key是函数的名称,value是函数本身。 Short example:
简短示例:
functions = { 'add' : lambda x,y : x + y, 'mult': lambda x,y : x * y, 'div' : lambda x,y : x / y, 'sub' : lambda x,y : x - y }
functions['add'](1,2) # returns 3
The *args
in the function file2_function
means the arguments to be passed to the function in which it calls: 函数
file2_function
的*args
表示要传递给调用它的函数的参数:
def func1(a):
print a
def file2_function(function,*args):
function(*args)
file2_function(func1,4)
#4
@aga gave you a good hint. @aga给了您一个很好的提示。 When I'm writing cli applications I usually do smth like:
当我编写cli应用程序时,我通常会像这样:
def func1():
pass
def func2():
pass
def func3():
pass
def func_caller(name):
func_dict = {
'func1': func1,
'func2': func2,
'func3': func3
}
try:
func_dict[name]()
except KeyError:
print "no such func"
Alternatively you have getattr
. 或者,您有
getattr
。 See following snippet: 请参见以下代码段:
>>> import sys
>>> getattr(sys,'exc_info')
<built-in function exc_info>
>>> getattr(sys,'exc_info')()
(None, None, None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.