码迷,mamicode.com
首页 > 编程语言 > 详细

python 类装饰器

时间:2017-03-22 16:33:11      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:xxx   sel   orm   trace   pytho   ace   rgs   nbsp   lan   

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)

python 类装饰器

标签:xxx   sel   orm   trace   pytho   ace   rgs   nbsp   lan   

原文地址:http://www.cnblogs.com/sysnap/p/6600397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!