标签: python-nonlocal

在Python <3中有类似'nonlocal'的东西吗?

我得到了一段这样的代码:

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() # ...
Run Code Online (Sandbox Code Playgroud)

我发现foo在最外面的scop中定义它很难看,我宁愿只在outer函数中使用它.据我所知,在Python3中,这是通过nonlocal.对于我想拥有的东西,有更好的方法吗?我更愿意申报和分配foo,outer并可能在delcare globalinner:

def outer():
    foo = 0

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

    id1 = make_id() # id = 1
    id2 = make_id() …
Run Code Online (Sandbox Code Playgroud)

python python-nonlocal

3
推荐指数
1
解决办法
294
查看次数

理解 Python 3 中的非本地

我试图理解 Python 3 变量范围和nonlocal.

考虑以下函数(这只是一个示例):

def build_property(something):

    def deco(func):

        def getter(self):
            return getattr(self, something)

        def setter(self, value):
            setattr(self, something, value)

        return property(getter, setter)

    return deco
Run Code Online (Sandbox Code Playgroud)

这在没有nonlocal. 但如果现在我想根据something我需要的非本地条件有条件地创建 getter 和 setter。

def build_property(something):

    def deco(func):

        nonlocal something # This is needed

        if something.startswith('A'):
            getter = None
        else:
            def getter(self):
                return getattr(self, something)

        if something.startswith('B'):
            setter = None
        else:
            def setter(self, value):
                setattr(self, something, value)

        return property(getter, setter)

    return deco
Run Code Online (Sandbox Code Playgroud)

为什么nonlocal在一种情况下需要,但在另一种情况下不需要?换句话说,为什么something如果在第一种情况下正确找到(没有nonlocal …

python scoping python-3.x python-nonlocal

2
推荐指数
1
解决办法
5592
查看次数

如何检查具有给定名称的变量是否为非本地变量?

给定堆栈框架和变量名称,如何判断该变量是否为非局部变量?例:

import inspect

def is_nonlocal(frame, varname):
    # How do I implement this?
    return varname not in frame.f_locals  # This does NOT work

def f():
    x = 1
    def g():
        nonlocal x
        x += 1
        assert is_nonlocal(inspect.currentframe(), 'x')
    g()
    assert not is_nonlocal(inspect.currentframe(), 'x')

f()
Run Code Online (Sandbox Code Playgroud)

python stack-frame python-3.x python-nonlocal

2
推荐指数
1
解决办法
62
查看次数

python nonlocal - 为什么有时需要它有时不需要

我知道为什么我们需要在 Python 中声明非本地,并且对下面的示例有点困惑。没有nonlocal records第276行,records第277行没有定义。不过records第289行可以使用,没有任何错误。 没有非本地的

下面是nonlocal的情况,效果很好。 与非本地

python python-nonlocal

2
推荐指数
1
解决办法
893
查看次数