• 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
  • 相关阅读:
    取消GridView/ListView item被点击时的效果 记录学习
    EditText 几种显示方式,固定行数,自适应行数
    Android 判断当前屏幕是横屏还是竖屏
    Android 用代码设置Shape,corners,Gradient
    Android 横屏不让输入法全屏显示
    js-JavaScript高级程序设计学习笔记7
    js-FCC算法-Pairwise
    js-JavaScript高级程序设计学习笔记6
    js-JavaScript高级程序设计学习笔记5
    js-自制轮播插件!
  • 原文地址:https://www.cnblogs.com/jiangjing/p/8379816.html
Copyright © 2020-2023  润新知