使用for循环定义多个功能-Python [英] Using for loop to define multiple functions - Python

查看:60
本文介绍了使用for循环定义多个功能-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I need to create 10 functions called add1, add2, ..., add10. For each i, addi takes in an integer x and outputs x+i.

当我尝试以下内容并评估add2(10)时,Python给了我一个NameError.

Python gave me a NameError when I tried the following and evaluated add2(10).

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

我知道上面的代码是错误的,因为我定义的addi函数是不可变的.我敢肯定,我所做的只是重新定义了addi 10次.如何快速定义这10个功能?

I know the above code is wrong, since the addi functions I've defined aren't mutable; I'm pretty sure all I've done is redefine addi 10 times. How can these 10 functions be quickly defined?

推荐答案

在这种情况下,将 functools.partial 与字典结合使用.

Use functools.partial combined with a dictionary in this situation.

我假设您确实想要做的事情比较复杂,因为对于此特定任务并不需要多个功能.

I assume what you really want to do is more complex, since multiple functions are not necessary for this specific task.

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 是一个高阶函数,它返回固定选定参数的输入函数.
  • It is good practice to store a variable number of related objects in a specially defined dictionary.
  • functools.partial is a higher order function which returns an input function with selected argument(s) fixed.

从评论中可以看到一个常见问题:

From the comments, a commonly asked question goes:

OP似乎在问是否只有更好的方法来执行 defadd1: ... def add2: ...虽然我同意您的解决方案,但我不同意这是当前问题的解决方案.--MooingRawr

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

我的简短答案:

使用 globals().update 污染名称空间是一个坏主意.特制集合中的相关变量.这是有道理的任何观点(可维护性,调用,修改等).– jpp

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的扩展答案:

@BoarGules's extend answer:

这不是一个好主意,因为它可以动态创建函数,但是它们只能由静态代码调用(否则,代码不会知道该怎么称呼),那么它们具有动态性又有什么意义呢?动态创建它们使代码难以阅读(您不能轻松地搜索函数定义),并不需要IDE麻烦他们来帮助您.您可以节省繁琐,重复的工作编码,但编程有时需要乏味且谨慎重复.努力和技巧会更好地花在加速编码(智能搜索/替换,宏等).– 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

这篇关于使用for循环定义多个功能-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆