装饰器


"""
    - 装饰器 简单介绍
    - 在加载的时候执行
    - 执行被装饰函数的时候执行内容

"""
import time
from functools import wraps
from collections import defaultdict


def decorator(fun):
    def wrapper():
        print('this is decorator:', decorator. __name__)
        fun()
        print('fun after:', fun.__name__)
    return wrapper


@decorator
def decorator_demo1():
    print('this is after decorator:', decorator_demo1.__name__)

decorator_demo1()


""" 装饰器加参数一 """


def decorator1(fun):
    def wrapper(*arg, **kw):
        print('start')
        print(arg, kw)
        fun(*arg, **kw)
        print(fun.__name__)
    return wrapper


@decorator1
def decorator_demo2(name, age):
    print('age:', age)
    print('name:', name)

decorator_demo2('dongli', 18)


""" 装饰器加参数二 """


def decorator3(char):
    @wraps  # 不改变函数名
    def decorator2(fun):
        def wrapper(*arg, **kw):
            print('start', char)
            fun(*arg, **kw)
            print('end')
        return wrapper
    return decorator2


@decorator3('test')
def decorator_demo3(name):
    print(name, decorator_demo3.__name__)

decorator_demo3('dongli')


""" 类作为装饰器 """


class decorator4:

    def __init__(self, name):
        self.name = name

    def __call__(self, fun):
        print(self.name)

        def wrapper():
            fun()
        return wrapper


@decorator4('dongli')
def decorator_demo4():
    print('Ok')

decorator_demo4()


""" 做个小练习 """


class Decorator:
    """ 提供日志, 运行时间, 验证用户名密码等"""
    def __init__(self, type_name, file_name='t.log'):
        self.file_name = file_name
        self.type_name = type_name

    def __call__(self, fun):
        @wraps(fun)
        def wrapper():
            if hasattr(self, self.type_name):
                method = getattr(self, self.type_name)
                method(fun)
        return wrapper

    def log(self, fun):
        with open(self.file_name, 'a') as f:
            f.write(fun())

    def check(self, fun):
        user = input('UserName:')
        pwd = input('PossWord:')
        if all([user == 'dongli', pwd == 'dongli']):
            fun()

    def run(self, fun):
        now = time.time()
        fun()
        now_time = time.time()
        print('run_time is', int(now_time-now))



@Decorator('log')
def decorator_demo5():
    return 'execute method'

decorator_demo5()


@Decorator('check')
def decorator_demo6():
    print('login OK ')

decorator_demo6()

@Decorator('run')
def decorator_demo7():
    print('test time:')
    time.sleep(3)

decorator_demo7()

"""路由小案例"""

class Route:
    def __init__(self):
        self.route_dic = defaultdict(lambda: 0)

    def route(self, key):
        @wraps(key)
        def warpper(fun):
            self.route_dic[key] = fun()
            return fun

        return warpper

    def run(self, name):
        if self.route_dic[name]:
            print(self.route_dic[name])


r = Route()


@r.route('index')
def index():
    return 'this is index'


@r.route('list_page')
def list_page():
    return 'this is list_page'


r.run('index')
r.run('list_page')


最后更新于:2018-06-09 23:02:28