python装饰器中变量的范围-更改参数 [英] Scope of variables in python decorators - changing parameters

查看:133
本文介绍了python装饰器中变量的范围-更改参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下带有参数的修饰符:

I have the following decorator with parameters:

from functools import wraps
def pdecor(p):
    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            p -= 1
            return fn(*args, **wargs)
        return wrapper
    return decorator

尝试使用装饰器结果:

>>> @pdecor(1)
... def run(): pass
...
>>> run()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in wrapper
UnboundLocalError: local variable 'p' referenced before assignment
>>>

为什么我不能更改 p

推荐答案

因为您在 p >包装器,Python会将包装器内的 p 视为本地的包装。在Python 3中,您可以使用 nonlocal p p 标记为从外部范围引用。在Python 2中,没有办法分配给中间p,尽管您可以通过将相同值作为关键字参数传递给嵌套函数来获得对同一值的引用(例如, def decorator(fn,p = p))。

Because you assign to p inside wrapper, Python treats the p inside wrapper as local to wrapper. In Python 3 you can use nonlocal p to mark p as referenced from an outer scope. In Python 2 there is no way to assign to the intermediate p, although you can get a reference to the same value by passing it into the nested functions as a keyword argument (e.g., def decorator(fn, p=p)).

但是,目前尚不清楚您在做什么。 p 仅在 pdecor 本地。 pdecor 之外的任何代码都无法访问 p ,因此,将其递减不会对其他任何代码产生任何影响。因此,无论是否可以递减 p ,它都不会真正完成任何事情。

However, it's not clear what you're getting at with this anyway. p is already only local to pdecor. No code outside pdecor can access p, so decrementing it won't have any effect on any code elsewhere. So whether you can decrement p or not, it won't really accomplish anything.

这篇关于python装饰器中变量的范围-更改参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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