简体   繁体   English

Python <3中是否有类似“ nonlocal”的东西?

[英]Is there something like 'nonlocal' in Python < 3?

I got a piece of code like this: 我得到了一段这样的代码:

foo = None

def outer():
    global foo
    foo = 0

    def make_id():
        global foo
        foo += 1
        return foo


    id1 = make_id() # id = 1
    id2 = make_id() # id = 2
    id3 = make_id() # ...

I find it ugly to have foo defined in the outermost scop, I would prefer to have it only in outer function. 我发现在最outer作用域中定义foo是很难的,我宁愿仅在outer函数中使用它。 As I understand correctly, in Python3 this is done by nonlocal . 正如我理解正确的,在Python3这是通过nonlocal Is there a better method for what I want to have? 我想拥有一种更好的方法吗? I would prefer to declare and assign foo in outer and maybe to delcare it global in inner : 我宁愿在outer声明和分配foo ,也可能在inner global声明它:

def outer():
    foo = 0

    def make_id():
        global foo
        foo += 1     # (A)
        return foo

    id1 = make_id() # id = 1
    id2 = make_id() # id = 2
    id3 = make_id() # ...

(A) does not work, foo seems to be searched in the outermost scope. (A)不起作用, foo似乎是在最外面的范围内搜索的。

I use 1-element lists for this purpose: 为此,我使用1元素列表:

def outer():
    foo = [0]
    def make_id():
        r = foo[0]
        foo[0] += 1
        return r
    return make_id

make_id = outer()
id1 = make_id()
id2 = make_id()
...

This is the same as using nonlocal , at the cost of a slightly more cumbersome syntax ( foo[0] instead of foo ). 这与使用nonlocal相同,但语法稍微麻烦一些( foo[0]而不是foo )。

No, have this as a parameter to your make_id function. 不,将其作为您的make_id函数的参数。 Even better put your id in a class, and have make_id as an instance method, and have that instance as a global (if you must). 甚至最好将您的id放在一个类中,并将make_id作为实例方法,并将该实例作为全局实例(如果需要)。

不,最好的替代方法是函数属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM