深入浅出分析Python装饰器用法
本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下:
用类作为装饰器
示例一
最初代码:
classbol(object):
def__init__(self,func):
self.func=func
def__call__(self):
return"{}".format(self.func())
classita(object):
def__init__(self,func):
self.func=func
def__call__(self):
return"{}".format(self.func())
@bol
@ita
defsayhi():
return'hi'
改进一:
classsty(object):
def__init__(self,tag):
self.tag=tag
def__call__(self,f):
defwraper():
return"<{tag}>{res}{tag}>".format(res=f(),tag=self.tag)
returnwraper
@sty('b')
@sty('i')
defsayhi():
return'hi'
改进二:
classsty(object):
def__init__(self,*tags):
self.tags=tags
def__call__(self,f):
defwraper():
n=len(self.tags)
return"{0}{1}{2}".format(('<{}>'*n).format(*self.tags),f(),('{}>'*n).format(*reversed(self.tags)))
returnwraper
@sty('b','i')
defsayhi():
return'hi'
print(sayhi())
改进三:
classsty(object):
def__init__(self,*tags):
self.tags=tags
def__call__(self,f):
defwraper(*args,**kwargs):
n=len(self.tags)
return"{0}{1}{2}".format(('<{}>'*n).format(*self.tags),f(*args,**kwargs),('{}>'*n).format(*reversed(self.tags)))
returnwraper
@sty('b','i')
defsay(word='Hi'):
returnword
print(say())
print(say('Hello'))
示例二
最初代码:
importthreading
importtime
classDecoratorClass(object):
def__init__(self):
self.thread=None
def__call__(self,func,*args,**kwargs):
defwrapped_func(*args,**kwargs):
curr_thread=threading.currentThread().getName()
self.thread=curr_thread
print('\nthreadnamebeforerunningfunc:',self.thread)
ret_val=func()
print('\nthreadnameafterrunningfunc:',self.thread)
returnret_val
returnwrapped_func
@DecoratorClass()
defdecorated_with_class():
print('runningdecoratedwclass')
time.sleep(1)
return
threads=[]
foriinrange(5):
t=threading.Thread(target=decorated_with_class)
threads.append(t)
t.setDaemon(True)#守护
t.start()
改进:进程锁
importthreading
importtime
classDecoratorClass(object):
def__init__(self):
self.thread=None
self.lock=threading.Lock()
def__call__(self,func,*args,**kwargs):
defwrapped_func(*args,**kwargs):
self.lock.acquire()
curr_thread=threading.currentThread().getName()
self.thread=curr_thread
print('threadnamebeforerunningfunc:',self.thread)
ret_val=func()
print('\nthreadnameafterrunningfunc:',self.thread)
self.lock.release()
returnret_val
returnwrapped_func
@DecoratorClass()
defdecorated_with_class():
print('Letmesleep1second...')
time.sleep(1)
return
threads=[]
foriinrange(5):
t=threading.Thread(target=decorated_with_class)
threads.append(t)
t.start()
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《PythonSocket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。