zoukankan      html  css  js  c++  java
  • python 类装饰器

    1 装饰器无参数

    class tracer: 

        def __init__(self,func): 

            self.calls = 0 

            self.func = func 

        def __call__(self,*args): 

            self.calls += 1 

            print('call %s to %s' %(self.calls, self.func.__name__)) 

            self.func(*args) 

     

    @tracer

    def spam(a, b, c): 

        print(a + b + c) 

     

    spam(1,2,3)

     

    2 装饰器带参数

    class tracer:  

        def __init__(self, *args):  

            self.calls = 0

            self.args = args

         

        def __call__(self, func):

            self.func = func

            def realfunc(*args):

                  self.calls += 1

                  print('call %s to %s' %(self.calls, self.func.__name__))

                  self.func(*args)

            return realfunc

     

    @tracer("xxxx")

    def spam(a, b, c):  

        print(a + b + c)  

     

    spam(1,2,3)

     

    spam(1,2,3)

    class tracer:      def __init__(self,func):          self.calls = 0          self.func = func      def __call__(self,*args):          self.calls += 1          print('call %s to %s' %(self.calls, self.func.__name__))          self.func(*args)   @tracerdef spam(a, b, c):      print(a + b + c)  
    spam(1,2,3)spam(1,2,3)

  • 相关阅读:
    [蓝桥杯][基础训练]报时助手
    [蓝桥杯][基础训练]分解质因数
    [蓝桥杯][基础训练]2n皇后问题
    [啊哈算法]我要做月老
    [啊哈算法]关键道路(图的割边)
    [啊哈算法]重要城市(图的割点)
    并查集
    栈数组与栈链表代码实现

    循环链表
  • 原文地址:https://www.cnblogs.com/sysnap/p/6600397.html
Copyright © 2011-2022 走看看