python - 函数装饰器中的名称修饰
问题描述
如果装饰器名称是 __double_leading_underscore 类型,我不能在与装饰器相同的模块中声明的类中使用装饰器。
用一个例子更容易解释:
# Just a pass-through
def __decorator(fn):
return fn
decorator = __decorator
class A(object):
@decorator
def test(self):
return 1
print(A().test())
# Prints 1
如果我@decorator
改变@__decorator
:
class A(object):
@__decorator
def test(self):
return 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in A
NameError: name '_A__decorator' is not defined
它试图__decorator
从类中查找。
有没有办法保持命名约定但引用模块而不是类?
解决方案
这是由于 Python 的名称修改造成的。根据文档
__spam 形式的任何标识符(至少两个前导下划线,最多一个尾随下划线)在文本上替换为 _classname__spam,其中 classname 是去掉前导下划线的当前类名。只要它出现在类的定义中,就无需考虑标识符的句法位置,就可以完成这种修饰。
重点补充。
当解释器@__decorator
在 class中看到时A
,它会忽略对 的绑定decorator
,用文本替换__decorator
并_A__decorator
尝试评估该标识符,从而为您提供NameError
.
推荐阅读
- java - N Queen的Java回溯程序:StackOverFlow错误
- python - 如何在 Qt 中制作可嵌套的可扩展小部件
- javascript - 如何在同一行上获得多个具有不同 ID 的进度条?
- reactjs - 如何保护公共存储桶中的一些文件/对象?
- python - 我得到 KeyError: 722 并且我找不到它的含义或如何解决它
- angular - 调用函数时如何修复“this”未定义
- firebase - 反应本机应用程序 firebase.auth() 不是函数
- powershell - 将 BIOS 设置导出到 CSV 文件时的数据类型问题
- javascript - NodeJS 和 Sharp,BMP 到 PNG 错误:输入文件包含不受支持的图像格式
- vue.js - 在使用 vue + vuex 进行开发时使用模拟数据