记录两个装饰器

统计函数被调用次数的装饰器

import functools


def counter(func):
    @functools.wraps(func)
    def tmp(*args, **kwargs):
        tmp.count += 1
        return func(*args, **kwargs)

    tmp.count = 0
    return tmp




@counter
def func():
    print(func.count)
 
func()  #1
func()  #2
func()  #3

类中的某个方法用于装饰类中的其他方法

from operator import methodcaller


def do_something(funName='other', a='hello', b='world'):
    def wrapper(fun):
        def inner(*args, **kwargs):
            cls = args[0]
            methodcaller(funName,a=a,b=b)(cls)
            print(f'调用了方法{funName},参数a={a},参数b={b}')
            return fun(*args, **kwargs)

        return inner

    return wrapper


class Clazz():
    @do_something()
    def func(self, x, y):
        c = x + y
        print('{}+{}={}'.format(x, y, c))

    @do_something(funName='other',a='你好',b='世界')
    def func2(self, x, y):
        c = x + y
        print('{}+{}={}'.format(x, y, c))

    def other(self, a, b):

        print(f'a is {a},b is {b}')


if __name__ == '__main__':

    c =Clazz()

    c.func(x=1,y=2)
# a is hello,b is world
# 调用了方法done,参数a=hello,参数b=world
# 1+2=3

    c.func2(x=100,y=200)
# a is 你好,b is 世界
# 调用了方法other,参数a=你好,参数b=世界
# 100+200=300

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 后续有时间可能会不断地补充一些知识点。 一:简要说说iOS内存管理 1:凡是使用 alloc, new或者new开...
    jozdee阅读 4,055评论 0 1
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,898评论 18 399
  • 由于篇幅原因,接上面的一篇继续:Android中高级开发工程师-面试记录-长期更新[https://www.jia...
    肖义熙阅读 6,298评论 15 27
  • 设计模式 一、单例模式 definition:保证一个类仅有一个实例,并提供一个访问它的全局访问点。 普通单例模式...
    了凡和纤风阅读 9,435评论 0 3
  • Java继承关系初始化顺序 父类的静态变量-->父类的静态代码块-->子类的静态变量-->子类的静态代码快-->父...
    第六象限阅读 6,445评论 0 9