Python:如何使用set参数创建函数指针?

fjl*_*fob 3 python function-pointers global-variables

我的问题:

鉴于以下内容:

def foo(a,b)
Run Code Online (Sandbox Code Playgroud)

我试图在传递'a'的列表时调用python'map'函数,但是使用'b'的设置值.

另一个相关的事实是'b'是用户输入,因此,我不能使用语法:

def foo(a,b='default value')
Run Code Online (Sandbox Code Playgroud)

我希望我的'map'调用看起来像这样:

map(foo_wrapper,list_for_a)
Run Code Online (Sandbox Code Playgroud)

其中'foo_wrapper'是一个接受'a'但使用指定'b'的用户的函数.

我不知道是否可以用这种方式指定函数指针并怀疑它们不能.

我对这个问题的解决方案使用全局变量,所以如果有一种更优雅的方式并且上面是不可能的,我也会将其标记为答案.

简而言之,这是我的解决方案:

b = ''
def foo(a,b):
  print b,a

def foo_wrapper(a):
  foo(a,b)

def main():
  if sys.argv[1]:
    a = ['John', 'Jacob', 'Jingle all the way']
    global b
    b = sys.argv[1]
    map(foo_wrapper,a)
Run Code Online (Sandbox Code Playgroud)

上面可能有一两个错字; 我正在简化我实际需要做的事情.

谢谢你的回复!

Sve*_*ach 7

您可以functools.partial()为此目的使用:

from functools import partial

def f(a, b):
    return a + b

x = range(10)
print map(partial(f, b=3), x)
Run Code Online (Sandbox Code Playgroud)

版画

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Run Code Online (Sandbox Code Playgroud)


Foo*_*Bah 7

你想要一些类似于currying的东西.你可以在这里使用lambda:

map(lambda x: f(x,3), a)
Run Code Online (Sandbox Code Playgroud)