python利用装饰器进行运算的实例分析
今天想用python的装饰器做一个运算,代码如下
>>>defmu(x): def_mu(*args,**kwargs): returnx*x return_mu >>>@mu deftest(x,y): print'%s,%s'%(x,y) >>>test(3,5) Traceback(mostrecentcalllast): File"<pyshell#111>",line1,in<module> test(3,5) File"<pyshell#106>",line3,in_mu returnx*x TypeError:unsupportedoperandtype(s)for*:'function'and'function'
原来是不能这样弄的 函数与函数是不能运算的啊!
怎么办呢?
In[1]:fromfunctoolsimportwraps In[2]:defmu(x): ...:@wraps(x) ...:def_mu(*args,**kwargs): ...:x,y=args ...:returnx*x ...:return_mu ...: In[3]:@mu ...:deftest(x,y): ...:print'%s,%s'%(x,y) ...: In[4]:test(3,4) Out[4]:9
Python装饰器(decorator)在实现的时候,有一些细节需要被注意。例如,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变)
Python的functools包中提供了一个叫wraps的decorator来消除这样的副作用。写一个decorator的时候,最好在实现之前加上functools的wrap,它能保留原有函数的名称和docstring。
以上所述就是本文的全部内容了,希望大家能够喜欢。