目錄
- 1. partial(func, /, *args, **kwargs)
- 2. partialmethod(func, /, *args, **kwargs)
- 3. update_wrapper(wrapper, warpped, assigned=WRAPPER_ASSIGNMEDTS, updated=WRAPPER_UPDATES)
- 4. wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updasted=WRAPPER_UPDATES)
- 5. singledispatch(func)
- 6. singledispatchmethod(func)
- 7. cached_property(func)
- 8. lru_cache(user_function) / lru_cache(maxsize=128, typed=False)
1. partial(func, /, *args, **kwargs)
- 封裝原函式并回傳一個
partial object物件, 可直接呼叫 - 固定原函式的部分引數, 相當于為原函式添加了固定的默認值
相當于如下代碼:
def partial(func, /, *args, **kwargs):
def newfunc(*fargs, **fkwargs):
newkwargs = {**kwargs, **fkwargs}
return func(*args, *fargs, **newkwargs)
newfunc.func = func
newfunc.args = args
newfunc.kwargs = kwargs
return newfunc
例如, 需要一個默認轉換二進制的int()函式:
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
2. partialmethod(func, /, *args, **kwargs)
- 與
partial用法相同, 專門用于類定義中(由于類定義中第一個引數默認需要self/cls, 所以partial不適用) - 在類中, 不論普通方法,
staticmethod,classmethod還是abstractmethod都適用
例如:
class Cell:
def __init__(self):
self._alive = False
@property
def alive(self):
return self._alive
def set_alive(self, state):
self._alive = bool(state)
set_alive = partialmethod(set_state, True)
set_dead = partialmethod(set_state, False)
>>> c = Cell()
>>> c.alive
False
>>> c.set_alive()
>>> c.alive
True
3. update_wrapper(wrapper, warpped, assigned=WRAPPER_ASSIGNMEDTS, updated=WRAPPER_UPDATES)
- 更新裝飾函式(wrapper), 使其看起來更像被裝飾函式(wrapped)
- 主要用在裝飾器中, 包裹被裝飾函式, 并回傳一個更新后的裝飾函式. 如果裝飾函式沒有更新, 那么回傳的函式的元資料將來自裝飾器, 而不是原始函式
- 兩個可選引數用來指定原始函式的哪些屬性直接賦值給裝飾函式, 哪些屬性需要裝飾函式做相應的更新. 默認值是模塊級常量
WRAPPER_ASSIGNMENTS(賦值裝飾函式的__module__,__name__,__qualname__,__annotations__和__doc__屬性)和WRAPPER_UpDATED(更新裝飾函式的__dict__屬性)
4. wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updasted=WRAPPER_UPDATES)
- 簡化呼叫
update_wrapper的程序, 作為裝飾器使用 - 相當于
partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)
例如:
def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
print('Calling decorated function')
return f(*args, **kwargs)
return wrapper
@my_decorator
def example():
"""Docstring"""
print('Called example function')
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
如果沒有使用wraps, 那么被裝飾函式的名字將會是wrapper, 而且原始函式example的檔案字串將會丟失.
5. singledispatch(func)
- 作為裝飾器使用, 將被裝飾函式轉換為一個泛函式(generic function)
- 根據第一個引數的型別分派執行不同的操作
例如:
@singledispatch
def fun(arg, verbose=False):
if verbose:
print('Let me just say,', end='')
print(arg)
@fun.register(int)
def _(arg, verbose=False):
if verbose:
print('Strength in numbers, eh?', end='')
print(arg)
@fun.register(list)
def _(arg, verbose=False)
if verbose:
print('Enumerate this: ')
for i, elem in enumerate(arg):
print(i, elem)
>>> fun('Hello World')
Hello World
>>> fun('test', verbose=True)
Let me just say, test
>>> fun(123, verbose=True)
Strength in numbers, eh? 123
>>> fun(['Issac', 'Chaplin', 'Mr Bean'], verbose=True)
Enumerate this:
0 Issac
1 Chaplin
2 Mr Bean
可以使用"函式型別注釋"替代上面顯式指定型別
@fun.register def _(arg: int, verbose=False): pass
6. singledispatchmethod(func)
- 將方法裝飾為泛函式
- 根據第一個非
self或非cls引數的型別分派執行不同的操作 - 可以與其他裝飾器嵌套使用, 但
singledispatchmethod,dispatcher.register必須在最外層 - 其他用法與
singledispatch相同
例如:
class Negator:
@singledispatchmethod
@classmethod
def neg(cls, arg):
raise NotImplementedError("Cannot negate a")
@neg.register
@classmethod
def _(cls, arg: int):
return -arg
@neg.register
@classmethod
def _(cls, arg: bool):
return not arg
7. cached_property(func)
- 將方法轉換為一個屬性, 與
@property相似 - 被裝飾的方法僅計算一次, 之后作為普通實體屬性被快取
- 要求實體擁有可變的
__dict__屬性(在元類或宣告的__slots__中未包含__dict__的類中不可用)
例如:
class DataSet:
def __init__(self, sequence_of_numbers):
self._data = https://www.cnblogs.com/thunderLL/p/sequence_of_numbers
@cached_property
def stdev(self):
return statistics.stdev(self._data)
@cached_property
def variance(self):
return statistics.variance(self._data)
cached_property的底層是一個非資料描述符, 在func第一次計算時, 將結果保存在實體的一個同名屬性中(實體的__dict__中), 由于實體屬性的優先級大于非資料描述符, 之后的所有呼叫只直接取實體屬性而不會再次計算
8. lru_cache(user_function) / lru_cache(maxsize=128, typed=False)
- 快取被裝飾函式的最近
maxsize次的呼叫結果 maxsize如果設定為None, LRU快取機制將不可用, 快取會無限增長.maxsize的值最好是2的n次冪- 由于底層使用字典快取結果, 所以被裝飾函式的引數必須可哈希.
- 不同的引數模式會分開快取為不用的條目, 例如
f(a=1, b=2)和f(b=2, a=1)就會作為兩次快取 - 如果
typed設定為True, 不同型別的函式引數將會被分開快取, 例如f(3)和f(3.0)
例如:
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/158898.html
標籤:Python
