日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python decorator模块_Python decorator module

發(fā)布時間:2023/12/19 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python decorator模块_Python decorator module 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用functool中的wraps,可以復制一些信息(__name__,__doc__,__module__, __dict__),但是signature還是會被改變(比如參數(shù)信息),要保留正確的參數(shù)信息,可以使用decorate,從接口上看decorate和update_wrapper相反,這和api的命名就有關了:

update_wrapper wrapper with wrapped.

decorate function with a caller function (the caller function describing the functionality of the decorator).

特別之處在于,decorate方法要求參數(shù)中的caller function具備完整的signature

The caller function must have signature (f, *args, **kw), and it must call the original function f with arguments args and kw, implementing the wanted capability (in this case, memoization)

以下面的例子來說,_memoize是caller function,memoize是decorator

def _memoize(func, *args, **kw):if kw: #frozenset is used to ensure hashability

key =args, frozenset(kw.items())else:

key=args

cache= func.cache #attribute added by memoize

if key not incache:

cache[key]= func(*args, **kw)returncache[key]defmemoize(f):"""A simple memoize implementation. It works by adding a .cache dictionary

to the decorated function. The cache will grow indefinitely, so it is

your responsability to clear it, if needed."""f.cache={}returndecorate(f, _memoize)>>>@memoize

...defheavy_computation():

... time.sleep(2)

...return "done"

>>> print(getargspec(heavy_computation))

ArgSpec(args=[], varargs=None, varkw=None, defaults=None)

使用decorator模塊可以防止更改signature,這樣decorator符合一個signature-preserving decorators的要求:

Callable objects which accept a function as input and return a function as output, with the same signature.

來看另外一個例子

def _trace(f, *args, **kw):

kwstr= ','.join('%r: %r' % (k, kw[k]) for k insorted(kw))print("calling %s with args %s, {%s}" % (f.__name__, args, kwstr))return f(*args, **kw)deftrace(f):return decorate(f, _trace)

先了解一下結(jié)構(gòu):

python中單下劃線開頭代表這是一個內(nèi)部函數(shù),這里是_trace;

_trace是decorator內(nèi)部描述裝飾器功能的一個函數(shù),也可以說是wrapper,f是那個wrapped;

與之前的memoize不同,這里的trace只返回內(nèi)部函數(shù)_trace,不聲明其余內(nèi)容;

所以可以加語法糖!使用@decorator就達到一樣的效果,將一個caller function轉(zhuǎn)換成一個signature-reserving decorator。

>>>@decorator

...def trace(f, *args, **kw):

... kwstr= ','.join('%r: %r' % (k, kw[k]) for k insorted(kw))

...print("calling %s with args %s, {%s}" % (f.__name__, args, kwstr))

...return f(*args, **kw)

.

總結(jié)

以上是生活随笔為你收集整理的python decorator模块_Python decorator module的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。