gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:28:59 24 4
gpt4 key购买 nike

假设我需要创建 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com