• 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
  • 相关阅读:
    combotree的总结(这个好)
    Extjs下拉树代码测试总结
    ExtJs 3 自定义combotree
    项目中EXTjs中运用到的下拉树
    EXTJS下拉树ComboBoxTree参数提交及回显方法
    Extjs window组件 拖动统制
    extjs grid数据改变后刷新的实现
    获取 ext grid 选中行 对象
    ext:grid分页,列宽度自动填满grid宽度
    pringBoot2.0启用https协议
  • 原文地址:https://www.cnblogs.com/jiangjing/p/8379816.html
Copyright © 2020-2023  润新知