Python裝飾器使用示例及實(shí)際應(yīng)用例子
測(cè)試1
deco運(yùn)行,但myfunc并沒(méi)有運(yùn)行
def deco(func):
print 'before func'
return func
def myfunc():
print 'myfunc() called'
myfunc = deco(myfunc)
測(cè)試2
需要的deco中調(diào)用myfunc,這樣才可以執(zhí)行
def deco(func):
print 'before func'
func()
print 'after func'
return func
def myfunc():
print 'myfunc() called'
myfunc = deco(myfunc)
測(cè)試3
@函數(shù)名 但是它執(zhí)行了兩次
def deco(func):
print 'before func'
func()
print 'after func'
return func
@deco
def myfunc():
print 'myfunc() called'
myfunc()
測(cè)試4
這樣裝飾才行
def deco(func):
def _deco():
print 'before func'
func()
print 'after func'
return _deco
@deco
def myfunc():
print 'myfunc() called'
myfunc()
測(cè)試5
@帶參數(shù),使用嵌套的方法
def deco(arg):
def _deco(func):
print arg
def __deco():
print 'before func'
func()
print 'after func'
return __deco
return _deco
@deco('deco')
def myfunc():
print 'myfunc() called'
myfunc()
測(cè)試6
函數(shù)參數(shù)傳遞
def deco(arg):
def _deco(func):
print arg
def __deco(str):
print 'before func'
func(str)
print 'after func'
return __deco
return _deco
@deco('deco')
def myfunc(str):
print 'myfunc() called ', str
myfunc('hello')
測(cè)試7
未知參數(shù)個(gè)數(shù)
def deco(arg):
def _deco(func):
print arg
def __deco(*args, **kwargs):
print 'before func'
func(*args, **kwargs)
print 'after func'
return __deco
return _deco
@deco('deco1')
def myfunc1(str):
print 'myfunc1() called ', str
@deco('deco2')
def myfunc2(str1,str2):
print 'myfunc2() called ', str1, str2
myfunc1('hello')
myfunc2('hello', 'world')
測(cè)試8
class作為修飾器
class myDecorator(object):
def __init__(self, fn):
print "inside myDecorator.__init__()"
self.fn = fn
def __call__(self):
self.fn()
print "inside myDecorator.__call__()"
@myDecorator
def aFunction():
print "inside aFunction()"
print "Finished decorating aFunction()"
aFunction()
測(cè)試9
class myDecorator(object):
def __init__(self, str):
print "inside myDecorator.__init__()"
self.str = str
print self.str
def __call__(self, fn):
def wrapped(*args, **kwargs):
fn()
print "inside myDecorator.__call__()"
return wrapped
@myDecorator('this is str')
def aFunction():
print "inside aFunction()"
print "Finished decorating aFunction()"
aFunction()
實(shí)例
給函數(shù)做緩存 --- 斐波拉契數(shù)列
from functools import wraps
def memo(fn):
cache = {}
miss = object()
@wraps(fn)
def wrapper(*args):
result = cache.get(args, miss)
if result is miss:
result = fn(*args)
cache[args] = result
return result
return wrapper
@memo
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print fib(10)
注冊(cè)回調(diào)函數(shù) --- web請(qǐng)求回調(diào)
class MyApp():
def __init__(self):
self.func_map = {}
def register(self, name):
def func_wrapper(func):
self.func_map[name] = func
return func
return func_wrapper
def call_method(self, name=None):
func = self.func_map.get(name, None)
if func is None:
raise Exception("No function registered against - " + str(name))
return func()
app = MyApp()
@app.register('/')
def main_page_func():
return "This is the main page."
@app.register('/next_page')
def next_page_func():
return "This is the next page."
print app.call_method('/')
print app.call_method('/next_page')
mysql封裝 -- 很好用
import umysql
from functools import wraps
class Configuraion:
def __init__(self, env):
if env == "Prod":
self.host = "coolshell.cn"
self.port = 3306
self.db = "coolshell"
self.user = "coolshell"
self.passwd = "fuckgfw"
elif env == "Test":
self.host = 'localhost'
self.port = 3300
self.user = 'coolshell'
self.db = 'coolshell'
self.passwd = 'fuckgfw'
def mysql(sql):
_conf = Configuraion(env="Prod")
def on_sql_error(err):
print err
sys.exit(-1)
def handle_sql_result(rs):
if rs.rows > 0:
fieldnames = [f[0] for f in rs.fields]
return [dict(zip(fieldnames, r)) for r in rs.rows]
else:
return []
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
mysqlconn = umysql.Connection()
mysqlconn.settimeout(5)
mysqlconn.connect(_conf.host, _conf.port, _conf.user, \
_conf.passwd, _conf.db, True, 'utf8')
try:
rs = mysqlconn.query(sql, {})
except umysql.Error as e:
on_sql_error(e)
data = handle_sql_result(rs)
kwargs["data"] = data
result = fn(*args, **kwargs)
mysqlconn.close()
return result
return wrapper
return decorator
@mysql(sql = "select * from coolshell" )
def get_coolshell(data):
... ...
... ..
線程異步
from threading import Thread
from functools import wraps
def async(func):
@wraps(func)
def async_func(*args, **kwargs):
func_hl = Thread(target = func, args = args, kwargs = kwargs)
func_hl.start()
return func_hl
return async_func
if __name__ == '__main__':
from time import sleep
@async
def print_somedata():
print 'starting print_somedata'
sleep(2)
print 'print_somedata: 2 sec passed'
sleep(2)
print 'print_somedata: 2 sec passed'
sleep(2)
print 'finished print_somedata'
def main():
print_somedata()
print 'back in main'
print_somedata()
print 'back in main'
main()
相關(guān)文章
Python中關(guān)于logging模塊的學(xué)習(xí)筆記
在本篇文章里小編給大家整理的是一篇關(guān)于Python中l(wèi)ogging模塊相關(guān)知識(shí)點(diǎn)內(nèi)容,有興趣的朋友們可以參考下。2020-06-06Python反爬實(shí)戰(zhàn)掌握酷狗音樂(lè)排行榜加密規(guī)則
最新的酷狗音樂(lè)反爬來(lái)襲,本文介紹如何利用Python掌握酷狗排行榜加密規(guī)則,本章內(nèi)容只限學(xué)習(xí),切勿用作其他用途!?。。。? 有需要的朋友可以借鑒參考下2021-10-10tensorflow保持每次訓(xùn)練結(jié)果一致的簡(jiǎn)單實(shí)現(xiàn)
今天小編就為大家分享一篇tensorflow保持每次訓(xùn)練結(jié)果一致的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02Python?OpenCV識(shí)別行人入口進(jìn)出人數(shù)統(tǒng)計(jì)
本文主要介紹了Python?OpenCV識(shí)別行人入口進(jìn)出人數(shù)統(tǒng)計(jì),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧<BR>2023-01-01Tensorflow實(shí)現(xiàn)將標(biāo)簽變?yōu)閛ne-hot形式
這篇文章主要介紹了Tensorflow實(shí)現(xiàn)將標(biāo)簽變?yōu)閛ne-hot形式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05python如何為創(chuàng)建大量實(shí)例節(jié)省內(nèi)存
這篇文章主要為大家詳細(xì)介紹了python如何為創(chuàng)建大量實(shí)例節(jié)省內(nèi)存,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03