深入淺出分析Python裝飾器用法
本文實(shí)例講述了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'
改進(jìn)一:
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'
改進(jìn)二:
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())
改進(jìn)三:
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) # 守護(hù)
t.start()
改進(jìn):進(jìn)程鎖
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入門(mén)與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
在Python 3中實(shí)現(xiàn)類型檢查器的簡(jiǎn)單方法
這篇文章主要介紹了在Python 3中實(shí)現(xiàn)類型檢查器的簡(jiǎn)單方法,包括對(duì)函數(shù)注解這個(gè)新特性的介紹,需要的朋友可以參考下2015-07-07
Django中的Model操作表的實(shí)現(xiàn)
這篇文章主要介紹了Django中的Model操作表的實(shí)現(xiàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
Python wxPython庫(kù)Core組件BoxSizer用法示例
這篇文章主要介紹了Python wxPython庫(kù)Core組件BoxSizer用法,結(jié)合實(shí)例形式分析了wxPython BoxSizer布局管理相關(guān)使用方法及操作注意事項(xiàng),需要的朋友可以參考下2018-09-09

