今天想用python的裝飾器做一個(gè)運(yùn)算,代碼如下
>>> def mu(x): def _mu(*args,**kwargs): return x*x return _mu >>> @mu def test(x,y): print '%s,%s' %(x,y) >>> test(3,5) Traceback (most recent call last): File "", line 1, in test(3,5) File " ", line 3, in _mu return x*x TypeError: unsupported operand type(s) for *: 'function' and 'function'
原來是不能這樣弄的? 函數(shù)與函數(shù)是不能運(yùn)算的啊!
怎么辦呢?
In [1]: from functools import wraps In [2]: def mu(x): ...: @wraps(x) ...: def _mu(*args,**kwargs): ...: x,y=args ...: return x*x ...: return _mu ...: In [3]: @mu ...: def test(x,y): ...: print '%s,%s' %(x,y) ...: In [4]: test(3,4) Out[4]: 9
Python裝飾器(decorator)在實(shí)現(xiàn)的時(shí)候,有一些細(xì)節(jié)需要被注意。例如,被裝飾后的函數(shù)其實(shí)已經(jīng)是另外一個(gè)函數(shù)了(函數(shù)名等函數(shù)屬性會(huì)發(fā)生改變)
Python的functools包中提供了一個(gè)叫wraps的decorator來消除這樣的副作用。寫一個(gè)decorator的時(shí)候,最好在實(shí)現(xiàn)之前加上functools的wrap,它能保留原有函數(shù)的名稱和docstring。
以上所述就是本文的 全部內(nèi)容了,希望大家能夠喜歡。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
