【发布时间】:2022-01-16 00:51:06
【问题描述】:
将类变量作为装饰器函数的参数传递会导致类名称为NameError。运行这个:
def log(prefix=None):
def decorator(function):
"""Decorates the function"""
def wrapper(*args, **params):
"""Wraps the function"""
name = "-".join([prefix, function.__name__])
result = function(*args, **params)
print(f"completed the execution of '{name}'")
return result
return wrapper
return decorator
class ExampleClass:
_CONSTANT = "test"
def __init__(self, x):
self._x = x
@log(prefix=ExampleClass._CONSTANT)
def product_of_number(self, y):
return self._x * y
if __name__ == "__main__":
x = ExampleClass(3)
x.product_of_number(4)
导致错误
Traceback (most recent call last):
File "/home/developer/reproduce_decorator_name_space.py", line 23, in <module>
class ExampleClass:
File "/home/developer/reproduce_decorator_name_space.py", line 31, in ExampleClass
@log(prefix=ExampleClass._CONSTANT)
NameError: name 'ExampleClass' is not defined
但是,运行这个
def log(prefix=None):
def decorator(function):
"""Decorates the function"""
def wrapper(*args, **params):
"""Wraps the function"""
name = "-".join([prefix, function.__name__])
result = function(*args, **params)
print(f"completed the execution of '{name}'")
return result
return wrapper
return decorator
_CONSTANT = "test"
class ExampleClass:
def __init__(self, x):
self._x = x
@log(prefix=_CONSTANT)
def product_of_number(self, y):
return self._x * y
if __name__ == "__main__":
x = ExampleClass(3)
x.product_of_number(4)
给出输出
completed the execution of 'test-product_of_number'
为什么ExampleClass 无法识别?装饰的方法在__init__ 之后的类中并引用了self。错误消息本身是指模块ExampleClass。类名怎么不存在于命名空间中?
【问题讨论】:
-
这能回答你的问题吗? Python - Referencing class name from inside class body。 TL;DR,名称
ExampleClass直到类块执行后才分配给。 -
你应该也可以在第一个sn-p中直接使用
@log(prefix=_CONSTANT)。
标签: python namespaces decorator