zoukankan      html  css  js  c++  java
  • functools模块学习

    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 = 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)
    
  • 相关阅读:
    根据 谷歌官网写一个 该浏览器上的扩展
    深度学习
    华为在线学习
    pandas 常规操作大全
    猎奇有些意思的
    LINUX 必知必会检测表--通读无关语言
    自动化部署三剑客 gitlab + ansible + jenkins
    python 框架
    delphi 多线程之System.TMonitor
    函数和对象 及 prototype和__proto__
  • 原文地址:https://www.cnblogs.com/thunderLL/p/12697672.html
Copyright © 2011-2022 走看看