Python中的嵌套函数 [英] Nested Function in Python

查看:107
本文介绍了Python中的嵌套函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这样的Python代码可以带来什么好处或影响?

What benefit or implications could we get with Python code like this:

class some_class(parent_class):
    def doOp(self, x, y):
        def add(x, y):
            return x + y
        return add(x, y)

我在一个开源项目中发现了这一点,它在嵌套函数内部做了一些有用的事情,但是除了调用它外,在嵌套函数之外什么也没做. (可以在此处.)为什么有人会这样编码?在嵌套函数内部而不是外部普通函数中编写代码是否有好处或副作用?

I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothing outside it except calling it. (The actual code can be found here.) Why might someone code it like this? Is there some benefit or side effect for writing the code inside the nested function rather than in the outer, normal function?

推荐答案

通常,您这样做是为了使 关闭 :

Normally you do it to make closures:

def make_adder(x):
    def add(y):
        return x + y
    return add

plus5 = make_adder(5)
print(plus5(12))  # prints 17

内部函数可以访问封闭范围中的变量(在这种情况下,是局部变量x).如果您不从封闭范围访问任何变量,那么它们实际上只是具有不同范围的普通函数.

Inner functions can access variables from the enclosing scope (in this case, the local variable x). If you're not accessing any variables from the enclosing scope, they're really just ordinary functions with a different scope.

这篇关于Python中的嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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