【问题标题】:Python decorator scopePython 装饰器作用域
【发布时间】:2017-09-18 09:37:45
【问题描述】:

我正在尝试理解 Python 中装饰器的逻辑,但我在局部变量的范围上遇到了问题。
代码:

# version #1
def decorator(function):
    counter = 0
    def wrapper():
        print(counter)
        function()
        return counter
    return wrapper

# version #2
def decorator(function):
    counter = 0
    def wrapper():
        counter += 1
        function()
        return counter
    return wrapper

@decorator
def function():
    print("Printed from function().")

function()

我的问题是,为什么#1 有效并且打印了counter,但是当我尝试在#2 中更改counter 时,我得到UnboundLocalError: local variable 'counter' referenced before assignment
谢谢!

【问题讨论】:

    标签: python-3.x scope decorator


    【解决方案1】:

    counter += 1counter = counter + 1 的一个糖,它定义了一个等于 1+counter 的变量 counter,此时该变量是未绑定的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 2013-08-07
      • 2014-01-23
      相关资源
      最近更新 更多