装饰器

函数装饰器:通常用于插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计

def use_logging(func):
    def wrapper(*args,**kwargs):
            print("logger is running")
            return func(*args)
    return wrapper

@use_logging
def foo():
    print("foo")

@use_logging
def bar():
    print("bar")


if __name__ == '__main__':
    bar()
    foo()

类装饰器:自动执行类中的call函数

class Foo(object):

def __init__(self,func):

    self._func = func

def __call__(self):

    print("class decorator runing")

    self._func()

    print("ending")

@Foo

def bar():

    print("bar")

if __name__ == '__main__':

    bar()

functools.wraps:复现函数的元信息

from functools import wraps

def logged(func):
    @wraps(func)
    def with_logging(*args,**kwargs):
            print (func.__name__ + "was called")
            return func(*args,**kwargs)
    return with_logging

@logged

def f(x):
    """
    does some math
    """
    return x+x*x

print (f.__name__)
print (f.__doc__)

你可能感兴趣的:(装饰器)