简体   繁体   English

Python:将函数传递给具有命名参数的函数

[英]Python: Pass function to function with named parameters

I am looking to pass a function to another function, as well as a named parameter. 我希望将一个函数以及另一个命名参数传递给另一个函数。 This is similar to the question asked here , except that it doesn't address named parameters. 这与此处提出的问题类似,除了它不解决命名参数。 A question was asked about it in the comments but no reply. 在评论中有人问了这个问题,但没有答复。

Example: 例:

def printPath(path, displayNumber = False):
    pass

def explore(path, function, *args):
    contents = function(*args)

print explore(path, printPath, path, displayNumber = False)

This gives the error: 这给出了错误:

TypeError: explore() got an unexpected keyword argument 'displayNumber'

You just have to allow explore to receive named parameters as well: 您只需要允许explore也接收命名参数:

def printPath(path, displayNumber = False):
    pass

def explore(path, function, *args, **kwargs):
    contents = function(*args, **kwargs)

print explore(path, printPath, path, displayNumber = False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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