python - 使用for循环定义多个函数——Python

标签 python python-3.x functional-programming

假设我需要创建 10 个名为 add1、add2、...、add10 的函数。对于每个 i,addi 接受一个整数 x 并输出 x+i

当我尝试以下操作并评估 add2(10) 时,Python 给了我一个 NameError。

for i in range(10):
    def addi(x):
        return x + (i+1)

我知道上面的代码是错误的,因为我定义的 addi 函数是不可变的;我很确定我所做的就是重新定义 addi 10 次。如何快速定义这10个功能?

最佳答案

在这种情况下使用 functools.partial 和字典。

我假设您真正想做的事情更复杂,因为对于这个特定任务而言,多个函数并不是必需的。

from functools import partial

def add(x, i):
    return x + i

d = {f'add{k}': partial(add, i=k) for k in range(1, 10)}

d['add3'](5)  # 8

解释

  • 最好在专门定义的字典中存储数量可变的相关对象。
  • functools.partial 是一个高阶函数,它返回一个带有固定选定参数的输入函数。

污染命名空间

从评论中,一个常见的问题是:

OP seems to be asking if there's a better way of just doing def add1:... def add2:... While I agree with your solution, I don't agree with the fact that it's the solution to the current question. - MooingRawr

Why is using an iterator to define functions a bad idea? It seemed like a good way to shorten code to me. Is it generally better to define them one by one? – jessica

我的简短回答:

Using globals().update to pollute the namespace is a bad idea.. Hold related variables in specially made collections. It makes sense from any viewpoint (maintainability, calling, modifying, etc). – jpp

@BoarGules 的扩展回答:

It's not a good idea because it creates functions dynamically, but they can only be called by static code (otherwise the code wouldn't know what to call), so what's the point of them being dynamic? Creating them dynamically makes the code hard to read (you can't easily search for the function definition) and gives IDEs unnecessary trouble in their efforts to help you. You save tedious, repetitive coding, but programming sometimes entails tedious and careful repetition. The effort and skill would be better spent speeding up the coding (clever search/replace, macros, whatever). – BoarGules

关于python - 使用for循环定义多个函数——Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49631178/

相关文章:

Haskell 读取前 n 行

python - 如何在 django 过滤器中使用选择字段值过滤对象

python - 我的字典有 9 个项目,但在迭代时只有 8 个

python - 带 pandas 的水平条形图左侧的输出表

python - 使用 Python 和 bsddb3 在 Berkeley DB 数据库中存储数据

python - 在 Python 中乘以字符串时使用 sep

javascript - 如何在不使用全局变量的情况下编辑待办事项列表 函数式编程 Vanilla JS

python - PySpark : Optimize read/load from Delta using selected columns or partitions

python - Django 更改 Photologue 的应用程序名称

java - java8流如何判断一个列表是否是另一个列表的子序列?