深入淺出分析Python裝飾器用法
更新時間:2017年07月28日 10:12:31 作者:羅兵
這篇文章主要介紹了Python裝飾器用法,結(jié)合實例形式對比分析了Python裝飾器的定義與使用技巧,需要的朋友可以參考下
本文實例講述了Python裝飾器用法。分享給大家供大家參考,具體如下:
用類作為裝飾器
示例一
最初代碼:
class bol(object):
def __init__(self, func):
self.func = func
def __call__(self):
return "<b>{}</b>".format(self.func())
class ita(object):
def __init__(self, func):
self.func = func
def __call__(self):
return "<i>{}</i>".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 "<{tag}>{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()
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python編譯結(jié)果之code對象與pyc文件詳解
今天小編就為大家分享一篇對Python編譯結(jié)果之code對象與pyc文件的詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-10-10

