day13.装饰器进阶

1.from functools import wraps

这个函数可以保留原来函数的属性

# from functools import wraps
def car_time(fun):
    # @wraps(fun)
    def inner(*args,**kwargs):
        ret = fun(*args,**kwargs)
        return ret
    return inner

@car_time
def car(some):
    """ 这是一个函数car的注释"""
    print(some)
    print(car.__name__)
    print(car.__doc__)

car('hello')

  hello
  inner
  None

在这是掉functools模块的调用以后,可以看出,我们调用的函数 car() 实际是闭包函数里面的inner()函数。如果加入functools模块呢

from functools import wraps
def car_time(fun):
    @wraps(fun)
    def inner(*args,**kwargs):
        print('装饰前')
        ret = fun(*args,**kwargs)
        print('装饰后')
        return ret
    return inner

@car_time
def car(some):
    """ 这是一个函数car的注释"""
    print(some)
    print(car.__name__)
    print(car.__doc__)

car('hello')
装饰前
hello
car
 这是一个函数car的注释
装饰后

亲爱的詹姆斯先生,神不知鬼不觉的给你加了个装饰器。没改变函数的任何属性,岂不是美滋滋?我们用了都说好

带参数的装饰器

在装饰器外面再加一层函数,三层函数调用。

def outer(形参):
    def wrapper(func):
        def inner(*args,**kwargs):
            ret = func(*args,**kwargs)   # func是被装饰的函数 在这里被调用
            return ret
        return inner
    return wrapper

@outer(实参)
def func():
    pass

多个装饰器装饰一个函数

猜你喜欢

转载自www.cnblogs.com/jiuyachun/p/10451059.html