我有这样的功能:
def activate_field_1():
print 1
def activate_field_2():
print 2
def activate_field_3():
print 3
Run Code Online (Sandbox Code Playgroud)
如何定义activate_field_[x]的x=1:10,而不打字了他们中的每一个?当然,我宁愿传递参数,但出于我的目的,这是不可能的.
谢谢!
Man*_*dan 19
您想要静态地在源文件中单独定义这些吗?那么你最好的选择就是编写一个脚本来生成它们.
另一方面,如果您希望在运行时使用这些函数,则可以使用更高阶函数.例如
>>> def make_func(value_to_print):
... def _function():
... print value_to_print
... return _function
...
>>> f1 = make_func(1)
>>> f1()
1
>>> f2 = make_func(2)
>>> f2()
2
Run Code Online (Sandbox Code Playgroud)
您可以在运行时再次生成这些列表并存储.
>>> my_functions = [make_func(i) for i in range(1, 11)]
>>> for each in my_functions:
... each()
...
1
2
3
...
Run Code Online (Sandbox Code Playgroud)
mar*_*eau 10
这里的函数名称与您想要的完全相同(并且比@ Goutham现在删除的答案中提到的动态/运行时方法创建的接受答案简单一些):
FUNC_TEMPLATE = """def activate_field_{0}(): print({0})"""
for x in range(1, 11): exec(FUNC_TEMPLATE.format(x))
>>> activate_field_1()
1
>>> activate_field_7()
7
Run Code Online (Sandbox Code Playgroud)
您可以将新符号放入由 返回的当前变量绑定字典中vars():
for i in range(1, 11):
def f(x):
def g():
print x
return g
vars()['activate_field_%d' % i] = f(i)
>>> activate_field_3()
3
Run Code Online (Sandbox Code Playgroud)
但是除非您确定需要它,否则通常不建议使用此技巧。
| 归档时间: |
|
| 查看次数: |
17277 次 |
| 最近记录: |