5.装饰器进阶篇
接着上一篇来
1.使用装饰器来验证函数参数的类型是否正确:
# -*- coding: utf-8 -*- #__author:jiangjing #date:2018/1/5
import functools # 构建装饰器 def params_chack(*types, **kwtypes): def outer(func): def inner(*args, **kwargs): result = [isinstance(_param, _type) for _param, _type in zip(args, types)] assert all(result), "params_chack: invalid parameters" result = [isinstance(kwargs[_param], kwtypes[_param]) for _param in kwargs if _param in kwtypes] assert all(result), "params_chack: invalid parameters" return func(*args, **kwargs) return inner return outer # 使用装饰器 @params_chack(int, str, c=(int, str)) def test(a, b, c): print("in function test04, a=%s, b=%s, c=%s" % (a, b, c)) return 1 # 测试用例 print(test(1, "str", 1)) # 参数正确 print(test(1, "str", "abc")) # 参数正确 print(test("str", 1, "abc")) # 参数错误
2.使用装饰器对一些计算非常耗时、复杂的结果进行缓存:
# -*- coding: utf-8 -*- #__author:jiangjing #date:2018/1/5 import time def func_cache(func): cache = {} def wrapper(*args): if args not in cache: print('没有命中缓存') cache[args] = func(args) else: print('命中缓存') return cache[args] return wrapper @func_cache def func(*args): #中间省略复杂的计算 sum = 0 for i in range(args[0][0]): sum = sum + i return sum print(func(100000000)) print(func(100000000))
输出结果为:
没有命中缓存
4999999950000000
命中缓存
4999999950000000
3.使用装饰器来实现单例模式
# -*- coding: utf-8 -*- #__author:jiangjing #date:2018/1/5 def singleton(cls): instance = {} def inner(*args, **kargs): if cls not in instance: instance[cls] = cls(*args, **kargs) return instance[cls] return inner @singleton class Test(object): def __init__(self, x = 0): self.x = x t1 = Test(2) t2 = Test(3) print(id(t1)) print(id(t2)) print(t1.x) print(t2.x) 输出为: 10309248 10309248 2 2
posted on 2018-01-29 22:31 后端bug开发工程师 阅读(128) 评论(0) 编辑 收藏 举报