装饰器

一. 装饰器

  在不改变原函数的调用方式和函数,额外的增加功能

  1. 简单装饰器

import time
def timer(func):
    def inner():
        print(time.time())
        func()
    return inner()

@timer
def func1():
    print('func1')

  2. 函数带返回值

import time
def timer(func):
    def inner():
        print(time.time())
        ret = func()
        return ret
    return inner

  3. 原函数携带参数

def download(func):
    def inner(*args, **kwargs):
        print('下载软件')
        func(*args, **kwargs)
    return inner

  4. 完整的装饰器的写法

def warpper(func):
    def inner(*args, **kwargs):
        print('inner')
        ret = func(*args, **kwargs)
        return ret
    return inner

@warpper
def func1():
    print('func1')

func1()

  5. 装饰器带参数

import time
flag = True

def outer(flag):
    def timer(func):
        def inner(*args, **kwargs):
            if flag:
                print(time.time())
                ret = func(*args, **kwargs)
            else:
                ret = func(*args, **kwargs)
            return ret
        return inner
    return timer

@outer(True)    #func1 = timer(func1) inner
def func1():
    print('func1')

func1()

  6. 多个装饰器装饰同一个函数

def wrapper1(func):
    def inner(*args, **kwargs):
        print('wrapper1 前')  # 2
        ret = func(*args, **kwargs)
        print('wrapper1 后')  # 4
        return ret
    return inner

def wrapper2(func):
    def inner(*args, **kwargs):
        print('wrapper2 前')  # 1
        ret = func(*args, **kwargs)
        print('wrapper2 后')  # 5
        return ret
    return inner

@wrapper2  # func1 = wrapper2(func1)  wrapper2.inner   func=wrapper1.inner
@wrapper1  # func1 = wrapper1(func1)  wrapper1.inner   func=func1
def func1():
    print('func1')  # 3
    return 'func1的返回值'

print(func1())  # 6

  7. 装饰器修复技术

import time
from functools import wraps
def timer(func):
    @wraps(func)
    def inner():
        print(time.time())
        ret = func()  # 原来的函数
        return ret
    return inner


@timer  # func1 = timer(func1)
def func1():
    """
    func1 xxxx
    :return:
    """
    print('func1')
    return 'func1的返回值'

@timer  # func1 = timer(func1)
def func2():
    """
    func2 xxxx
    :return:
    """
    print('func2')
    return 'func2的返回值'

print(func1.__name__)
print(func2.__name__)
print(func2.__doc__)

 

posted @ 2018-12-04 19:08  孔辉  阅读(142)  评论(0编辑  收藏  举报