从通用函数定义函数列表

Jos*_*osh 3 python metaprogramming decorator

说我有一个功能

def my_meta_function (a, b, c):
  pass
Run Code Online (Sandbox Code Playgroud)

我想定义一个函数数组myfunctions = [f1, f2, f3, ... f100],其中参数c固定为每个这样的函数的不同值,例如c = [1,2,3, .. 100],函数只接受参数ab.在实践中,我正在考虑的论点更复杂,但我试图理解如何在语言中这样做.

  • 这种类型的元编程有名字吗?
  • 装饰者是否适合这个?如果没有,为什么?

Ash*_*ary 6

用途functools.partial:

>>> from functools import partial
def func(a, b, c):
...     print a, b, c
...     
>>> funcs = [partial(func, c=i) for i in xrange(5)]
>>> funcs[0](1, 2)
1 2 0
>>> funcs[1](1, 2)
1 2 1
>>> funcs[2](1, 2)
1 2 2
Run Code Online (Sandbox Code Playgroud)

出于学习目的,您也可以使用以下方法lambda:

>>> funcs = [lambda a, b, i=i:func(a, b, c=i) for i in xrange(5)]
>>> funcs[0](1, 2)
1 2 0
>>> funcs[1](1, 2)
1 2 1
Run Code Online (Sandbox Code Playgroud)

但你不应该使用它,为什么?: