python装饰器用法_深入浅出分析Python装饰器用法
本文實例講述了Python裝飾器用法。分享給大家供大家參考,具體如下:
用類作為裝飾器
示例一
最初代碼:
class bol(object):
def __init__(self, func):
self.func = func
def __call__(self):
return "{}".format(self.func())
class ita(object):
def __init__(self, func):
self.func = func
def __call__(self):
return "{}".format(self.func())
@bol
@ita
def sayhi():
return 'hi'
改進一:
class sty(object):
def __init__(self, tag):
self.tag = tag
def __call__(self, f):
def wraper():
return "{res}{tag}>".format(res=f(), tag=self.tag)
return wraper
@sty('b')
@sty('i')
def sayhi():
return 'hi'
改進二:
class sty(object):
def __init__(self, *tags):
self.tags = tags
def __call__(self, f):
def wraper():
n = len(self.tags)
return "{0}{1}{2}".format((''*n).format(*self.tags), f(), ('{}>'*n).format(*reversed(self.tags)))
return wraper
@sty('b', 'i')
def sayhi():
return 'hi'
print(sayhi())
改進三:
class sty(object):
def __init__(self, *tags):
self.tags = tags
def __call__(self, f):
def wraper(*args, **kwargs):
n = len(self.tags)
return "{0}{1}{2}".format((''*n).format(*self.tags), f(*args, **kwargs), ('{}>'*n).format(*reversed(self.tags)))
return wraper
@sty('b', 'i')
def say(word='Hi'):
return word
print(say())
print(say('Hello'))
示例二
最初代碼:
import threading
import time
class DecoratorClass(object):
def __init__(self):
self.thread = None
def __call__(self, func, *args, **kwargs):
def wrapped_func(*args, **kwargs):
curr_thread = threading.currentThread().getName()
self.thread = curr_thread
print('\nthread name before running func:', self.thread)
ret_val = func()
print('\nthread name after running func:', self.thread)
return ret_val
return wrapped_func
@DecoratorClass()
def decorated_with_class():
print('running decorated w class')
time.sleep(1)
return
threads = []
for i in range(5):
t = threading.Thread(target=decorated_with_class)
threads.append(t)
t.setDaemon(True) # 守護
t.start()
改進:進程鎖
import threading
import time
class DecoratorClass(object):
def __init__(self):
self.thread = None
self.lock = threading.Lock()
def __call__(self, func, *args, **kwargs):
def wrapped_func(*args, **kwargs):
self.lock.acquire()
curr_thread = threading.currentThread().getName()
self.thread = curr_thread
print('thread name before running func:', self.thread)
ret_val = func()
print('\nthread name after running func:', self.thread)
self.lock.release()
return ret_val
return wrapped_func
@DecoratorClass()
def decorated_with_class():
print('Let me sleep 1 second...')
time.sleep(1)
return
threads = []
for i in range(5):
t = threading.Thread(target=decorated_with_class)
threads.append(t)
t.start()
希望本文所述對大家Python程序設計有所幫助。
總結
以上是生活随笔為你收集整理的python装饰器用法_深入浅出分析Python装饰器用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python eval函数格式_Pyth
- 下一篇: php 正则匹配静态资源,Struts2