从父函数传递参数嵌套函数的Python [英] Passing argument from Parent function to nested function Python

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

问题描述

这是我的code:

def f(x):
    def g(n):
        if n < 10:
            x = x + 1
            g(n + 1)
    g(0)

当我评估F(0),将有一个错误任务提前X引用。

When I evaluate f(0), there would be an error "x referenced before assignment".

然而,当我使用打印X,而不是X = X + 1时,它会工作。

However, when I use "print x" instead of "x = x + 1" , it will work.

看来,在G的范围,我只能用x作为一个使用事件,而不是一个具有约束力的发生。我想这个问题是F通过与G仅x的值。

It seems that in the scope of g, I can only use x as an "use occurrence" but not a "binding occurrence". I guess the problem is that f passes to g only the VALUE of x.

我是否正确或者不理解吗?如果不是,有人可以解释为什么左侧的X = X + 1没有引用之前定义的?

Am I understanding it correctly or not? If not, can someone explain why the left side of "x = x + 1" is not defined before reference?

感谢

推荐答案

您正确地理解它。不能使用 X 分配给在嵌套范围在Python 2。

You are understanding it correctly. You cannot use x to assign to in a nested scope in Python 2.

在Python 3里,你仍然可以通过标记变量外地使用它作为一个具有约束力的发生;这是引入了眼前这个用例关键字:

In Python 3, you can still use it as a binding occurrence by marking the variable as nonlocal; this is a keyword introduced for just this usecase:

def f(x):
    def g(n):
        nonlocal x
        if n < 10:
            x = x + 1
            g(n + 1)
    g(0)

在Python 2里,你有一些变通;采用可变,以避免需要使用的功能属性绑定,或(AB):

In python 2, you have a few work-arounds; using a mutable to avoid needing to bind it, or (ab)using a function property:

def f(x):
    x = [x]   # lists are mutable
    def g(n):
        if n < 10:
            x[0] = x[0] + 1   # not assigning, but mutating (x.__setitem__(0, newvalue))
            g(n + 1)
    g(0)

def f(x):
    def g(n):
        if n < 10:
            g.x = g.x + 1
            g(n + 1)
    g.x = x  # attribute on the function!
    g(0)

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

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