【问题标题】:Decorator running error: "UnboundLocalError: local variable 'count' referenced before assignment"装饰器运行错误:“UnboundLocalError:分配前引用的局部变量'count'”
【发布时间】:2019-12-02 16:53:18
【问题描述】:

我在两个不同的装饰器中创建了两个变量,一个装饰器运行良好,但另一个显示错误。

def running_average(func):
    data = {'total': 0, 'count': 0}
    def wrapper(*args, **kwargs):
        print(data)
        val = func(*args, **kwargs)
        data['total'] += val
        data['count'] += 1
        print('Average of {} so far: {:.01f}'.format(func.__name__,
              data['total']/data['count']))
        return func(*args, **kwargs)
    return wrapper

@running_average
def foo(x):
    return x + 2

这个 foo 函数有效。

def countcalls(func):
    count = 0
    print(count)
    def wrapper(*args, **kwargs):
        print(count)
        count += 1
        print('# of calls: {}'.format(count))
        return func(*args, **kwargs)
    return wrapper

@countcalls
def boo(x):
    return x + 2

但是这个boo 函数显示错误:UnboundLocalError: local variable 'count' referenced before assignment。

据我了解,这两个函数遵循相同的模式。在这两个装饰器中,在装饰器中都定义了一个变量,并且在包装函数中使用了该变量。但是,这个foo 功能很好,但是这个boo 功能不起作用。我想知道是什么原因?

【问题讨论】:

    标签: python decorator


    【解决方案1】:

    不同的是,在第一个例子中,名字data总是指同一个对象;它永远不会被重新分配。 data 所指的字典本身已发生变异(已更改),但始终是同一个对象。

    相比之下,当您在第二个示例中执行 count += 1 时,会更改名称 count 所指的值。这使得count 成为局部变量。当解释器看到这一点时,它会注意到您在分配给它之前引用了局部变量count,并且失败了。

    解决方案是通过声明 nonlocal 来告诉解释器使用封闭范围中的 count

    def countcalls(func):
        count = 0
        print(count)
        def wrapper(*args, **kwargs):
            nonlocal
            print(count)
            count += 1
            print('# of calls: {}'.format(count))
            return func(*args, **kwargs)
        return wrapper
    

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2019-10-10
      • 2019-09-11
      • 2017-08-10
      • 2020-01-16
      • 2019-12-05
      相关资源
      最近更新 更多