Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 作为函数参数运行任意代码(类似于lambda)_Python_Lambda - Fatal编程技术网

Python 作为函数参数运行任意代码(类似于lambda)

Python 作为函数参数运行任意代码(类似于lambda),python,lambda,Python,Lambda,我想在参数中运行任意“代码”,比如Python中的匿名函数。 如何在一行中实现这一点? Lambdas似乎不起作用,因为它们只接受一个表达式 def call_func(callback): callback() def f(): pkg_set_status(package_name, status) print('ok') call_func(f) 更新: 添加一些背景,因为我认为这个问题并不完全清楚 我想运行多行lambda或匿名函数之类的函数。 比如: ca

我想在参数中运行任意“代码”,比如Python中的匿名函数。 如何在一行中实现这一点? Lambdas似乎不起作用,因为它们只接受一个表达式

def call_func(callback):
    callback()

def f():
    pkg_set_status(package_name, status)
    print('ok')

call_func(f)
更新: 添加一些背景,因为我认为这个问题并不完全清楚

我想运行多行lambda或匿名函数之类的函数。 比如:

call_func(lambda:
   # my multiline code here
   pkg_set_status(package_name, status)
   print('ok')
)
所以参数本身就是匿名函数体

更新2:在这里找到了答案
看起来python在设计上不支持多行lambda。

它确实很简单-函数,只需在参数名后使用()

请记住,在Python中,函数和任何其他Python对象一样,您可以传递它们

def func():
    """Silly test function"""
    print('Running func')
    return 42

def call_something(callable):
    """Call something if we can"""
    # Sanity check before calling - not neccessary if you trust the caller
    if callable(callable):
       return callable()

# Use call_something to call func
call_something(func)

这个怎么样?您可以对每个表达式执行lambda,并将它们作为单独的参数传递给超级函数:

def call_everything(*funcs):
    for func in funcs:
        func()


call_everything(lambda: print('ok'), lambda: print('hi!'))


self.call\u func(f())
这不是我想要实现的,call\u func显然可以调用callable()。现在还不清楚你想要实现什么。从您后来添加到问题中的注释来看,您似乎想要一个多行lambda——这在Python中是不可能的,并且不打算添加它。Python不是Javascript。老实说,如果某件事情足够复杂,需要多行代码,那么它就足够复杂,需要一个名称:这就是我的观点。是的,这就是我试图实现的,但老实说,代码看起来像狗屎。