zoukankan      html  css  js  c++  java
  • 采用__call__ 实现装饰器模式

    装饰器模式在实现中也是很常见的:比如手机贴膜,手机壳 都是为了给手机增加一些额外功能 增加耐操

    装饰器模式的本质就是对对象二次包装,赋额外功能

    __call__

    __call__是python魔术方法——可调用对象,指的是可以实现一个对象实例以函数的方式来调用。

    class Test:
        def __call__(self, *args, **kws):
            print(*args, **kws)
    
    
    t = Test()
    
    t("你好","hello word")

    无参数装饰器

    现在有一个out函数,用于打印输出。现在要想要统计这函数执行了多少次

    class Count:
        def __init__(self,func):
            self.func = func
            self.i = 0
    
        def __call__(self,*args,**kws):
            self.i += 1
            print(f"执行次数:{self.i}")
            return self.func(*args,**kws)
    
    @Count
    def out(s):
        print(s)
    
    out("你好")
    out("呵呵")

    '''
    相当于
    out = Count(out)   
    out()
    把函数传入Count类中,创建对象实例 然后利用__call__魔术方法实现执行可调用对象
    '''

    有参数装饰器

    现在Count类有一个属性color,给统计数值上颜色。

    class Count:
        def __init__(self, color):
            self.color = color
            self.i = 0
    
        def __call__(self, func):
            self.func = func
            return self.__callback
    
        def __callback(self, *args, **kw):
            self.i += 1
            print(f"执行次数:{self.color} {self.i}")
            return self.func(*args, **kw)
    
    
    @Count("红色")   # 接收参数
    def test(s):
        print(s)
    
    
    test("哈哈") 

    '''
    等价于
    d = Count("红色")
    test = d(test)
    test("哈哈")
    '''
    test(
    "哈哈") test("哈哈")

    ''' 输出
    执行次数:红色 1
    哈哈
    执行次数:红色 2
    哈哈
    执行次数:红色 3
    哈哈
    '''
  • 相关阅读:
    Makefile 跟着走快点
    MariaDB 复合语句和优化套路
    Unity Shader常用函数,标签,指令,宏总结(持续更新)
    ThreadLocal 简述
    Java全排列排序
    Thrift入门
    Nginx + Keepalived 双机热备
    Linux 虚拟IP
    Java 反编译
    Spring拦截器
  • 原文地址:https://www.cnblogs.com/whnba/p/11917393.html
Copyright © 2011-2022 走看看