[英]Class not recognized in decorator arguments
将 class 变量作为装饰器 function 的参数传递会导致 class 名称的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)
给出 output
completed the execution of 'test-product_of_number'
为什么无法识别ExampleClass
? 装饰方法在__init__
之后的 class 内并引用 self。 错误消息本身是指模块ExampleClass
。 class 名称如何不存在于名称空间中?
装饰器可以访问ExampleClass
,可能不需要将参数传递给装饰器:
def log(prefix=''):
def decorator(function):
"""Decorates the function"""
def wrapper(*args, **params):
"""Wraps the function"""
# args[0] references the decorated class
if prefix:
# Option2: Prefix passed as string
name = "-".join(
[getattr(args[0], prefix, ''), function.__name__])
else:
# Option1: No prefix
name = "-".join([args[0]._CONSTANT, function.__name__])
result = function(*args, **params)
print(f"completed the execution of '{name}'")
return result
return wrapper
return decorator
class ExampleClass:
_CONSTANT = "test"
_ANOTHER_CONSTANT = "test2"
def __init__(self, x):
self._x = x
@log()
def product_of_number(self, y):
return self._x * y
@log('_ANOTHER_CONSTANT')
def product_of_anothernumber(self, y):
return self._x * y
if __name__ == "__main__":
x = ExampleClass(3)
x.product_of_number(4)
x.product_of_anothernumber(4)
出去:
completed the execution of 'test-product_of_number'
completed the execution of 'test2-product_of_anothernumber'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.