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)
?
?
轉載于:https://www.cnblogs.com/sysnap/p/6600397.html
總結
以上是生活随笔為你收集整理的python 类装饰器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Socket编程实践(3) 多连接服务
- 下一篇: python中对列表浅复制深复制另类的理