亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

Python裝飾器使用示例及實(shí)際應(yīng)用例子

系統(tǒng) 1659 0

測試1

deco運(yùn)行,但myfunc并沒有運(yùn)行

復(fù)制代碼 代碼如下:

def deco(func):
??? print 'before func'
??? return func

def myfunc():
??? print 'myfunc() called'
?
myfunc = deco(myfunc)

測試2

需要的deco中調(diào)用myfunc,這樣才可以執(zhí)行

復(fù)制代碼 代碼如下:

def deco(func):
??? print 'before func'
??? func()
??? print 'after func'
??? return func

def myfunc():
??? print 'myfunc() called'
?
myfunc = deco(myfunc)

測試3

@函數(shù)名 但是它執(zhí)行了兩次

復(fù)制代碼 代碼如下:

def deco(func):
??? print 'before func'
??? func()
??? print 'after func'
??? return func

@deco
def myfunc():
??? print 'myfunc() called'

myfunc()

測試4

這樣裝飾才行

復(fù)制代碼 代碼如下:

def deco(func):
??? def _deco():
??????? print 'before func'
??????? func()
??????? print 'after func'
??? return _deco

@deco
def myfunc():
??? print 'myfunc() called'
?
myfunc()

測試5

@帶參數(shù),使用嵌套的方法

復(fù)制代碼 代碼如下:

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()

測試6

函數(shù)參數(shù)傳遞

復(fù)制代碼 代碼如下:

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')

測試7

未知參數(shù)個數(shù)

復(fù)制代碼 代碼如下:

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')

Python裝飾器使用示例及實(shí)際應(yīng)用例子_第1張圖片

測試8

class作為修飾器

復(fù)制代碼 代碼如下:

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()

測試9

復(fù)制代碼 代碼如下:

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ù)列

復(fù)制代碼 代碼如下:

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)

注冊回調(diào)函數(shù) --- web請求回調(diào)

復(fù)制代碼 代碼如下:

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封裝 -- 很好用

復(fù)制代碼 代碼如下:

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):
??? ... ...
??? ... ..

線程異步

復(fù)制代碼 代碼如下:

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()


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 国产亚洲欧洲国产综合一区 | 成人免费观看高清在线毛片 | 天天爱夜夜操 | 免费中文字幕不卡视频 | 亚洲精品国产美女在线观看 | 一级高清毛片 | 一本一本久久a久久精品综合 | 黄片毛片免费在线观看 | 欧美一级毛片特黄大 | 久久免费视频观看 | 欧洲成人免费视频 | 亚洲一区二区三区国产精品 | 久久国产高清一区二区三区 | 在线看的成人性视频 | 国产激情久久久久影 | 成人区精品一区二区毛片不卡 | heyzo在线播放4k岛国 | 亚洲国产精品日韩一线满 | 欧美日韩国产在线观看 | 色综合久久一区二区三区 | 日韩欧美精品综合一区二区三区 | 精品久久在线观看 | 国产丰满老厨女房乱 | 两性视频久久 | 99re6这里有精品热视频在线 | 激情婷婷在线 | 日韩欧美在线免费观看 | 一区二区三区免费在线 | 一级片免费网站 | 久久精品国产一区二区 | 香蕉成人国产精品免费看网站 | 日本免费不卡视频 | 亚洲一区二区三区四 | 国产乳摇福利视频在线观看 | 天天操综合视频 | 欧美日韩亚洲一区二区 | 久久精品一区二区国产 | www.一区 | 欧美精品中文字幕手机免费视频 | 国产小视频免费在线观看 | 中文字幕热久久久久久久 |