Python decorator,无需将函数作为参数传递
我正在学习编写python装饰程序。下面是两个例子 例1:Python decorator,无需将函数作为参数传递,python,decorator,Python,Decorator,我正在学习编写python装饰程序。下面是两个例子 例1: def dec(): def wrapper(func): print(func) return func return wrapper @dec def hello(): print('hello') 例2: def dec(name): def wrapper(fn): print(fn) return fn return
def dec():
def wrapper(func):
print(func)
return func
return wrapper
@dec
def hello():
print('hello')
例2:
def dec(name):
def wrapper(fn):
print(fn)
return fn
return wrapper
@dec('a')
def hello(x):
print(x)
所以我的问题是,为什么示例1抛出一个异常,即
dec()接受0个位置参数,但给出了1,而示例2运行良好。Bot示例不正确。decorator的外部函数(本例中为dec)必须接受一个参数,该参数就是它所修饰的函数
因此,示例1应该如下所示:
def dec(func):
def wrapper():
print(func)
return func
return wrapper
@dec
def hello():
print('hello')
hello()
def dec_args(name):
def dec(func):
def wrapper():
print(func)
print(name)
return func
return wrapper
return dec
@dec_args('a')
def hello():
print('hello')
hello()
示例2 while不会立即崩溃,如果您尝试调用hello
(修饰函数),则会崩溃。
对于一个装饰者来说,你需要另一个层次的嵌套。
因此,示例2应该如下所示:
def dec(func):
def wrapper():
print(func)
return func
return wrapper
@dec
def hello():
print('hello')
hello()
def dec_args(name):
def dec(func):
def wrapper():
print(func)
print(name)
return func
return wrapper
return dec
@dec_args('a')
def hello():
print('hello')
hello()
内部装饰函数(wrapper
)应采用传递给装饰函数(hello
)的参数。在这种情况下,你没有任何
还要注意,包装器
函数实际上不需要返回func
wrapper
本质上是func
的替代品。装饰师就是这么做的。它们将您修饰的函数替换为修饰器的内部函数(通过使用修饰函数作为参数调用外部函数)。在第一个示例中,您需要像这样调用dec
:@dec()
。如果您想像您一样使用它,那么您的装饰器本身必须接受该函数(即不需要包装器)。