代码如下
def my_dec(func):
def wrap(w):
t = func(w)
return t * 4
return wrap
@my_dec
def testing(n):
return n
new = testing(3)
print(new) # This prints 12
这个例子工作正常,但现在我尝试将以下内容添加到装饰器中@my_dec(100)
,我需要将给定的数字乘以 100。
当我尝试这个时
@my_dec(100)
def testing(n):
return n
我收到以下错误:
Traceback (most recent call last):
File "./deco2", line 10, in <module>
@my_dec(100)
File "./deco2", line 5, in wrap
t = func(w)
TypeError: 'int' object is not callable
我怎样才能通过100
给装饰者?
在第一个示例中,您正确地将装饰器定义为一个函数,该函数接受包装的函数并返回一个新函数。
要添加参数,您需要编写一个接受参数的函数,并且返回装饰器,即返回接受包装函数并返回一个函数的函数。
一种方法是:
def my_dec(x):
def dec(func):
def wrap(w):
t = func(w)
return t * x
return wrap
return dec
如果您考虑一下什么,这可能会稍微清楚一些@
语法扩展为:
@my_dec(100)
def testing(n):
return n
扩展到:
def testing(n):
return n
testing = my_dec(100)(testing)
此外,为了减少高嵌套级别并使装饰器更具可读性和可维护性,您可以定义一个装饰器类,该类在其__init__
,并在其中调用包装函数__call__
。网上有很多例子。你可以从阅读开始这个问题 https://stackoverflow.com/q/666216/2096752.
还有一些方法可以让您的装饰器采用可选参数(即,以便您的两个示例都有效)。
如果你真的想深入了解装饰器,请阅读格雷厄姆·邓普尔顿的博客 https://github.com/GrahamDumpleton/wrapt/tree/master/blog。强烈推荐。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)