歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python中的裝飾器

Python中的裝飾器

日期:2017/3/1 9:30:53   编辑:Linux編程

什麼是裝飾器

假設有函數A,B,C,已經全部編寫完成,這時你發現A, B, C都需要同一個功能,這時該怎麼辦?

答: 裝飾器

裝飾器其實就是一個函數,不過這個函數的返回值是一個函數

個人理解,裝飾器主要就是為了完成上邊的這個功能,將A, B, C 函數包裹在另一個函數D中,D函數在A函數執行之前或之後,處理一些事情

#!/usr/bin/env python
#coding:utf-8
def SeparatorLine():
print "############################"

#裝飾器帶參數函數帶參數
def DecratorArgFuncArg(f1,f2):
def inner(func):
def wrapper(arg):
print "裝飾器帶參數函數帶參數"
f1()
result = func(arg)
f2()
return result
return wrapper
return inner

#裝飾器帶參數函數不帶參數
def DecratorArgFuncNoArg(f1,f2):
def inner(func):
def wrapper():
print "裝飾器帶參數函數不帶參數"
f1()
result=func()
f2()
return result
return wrapper
return inner

#函數沒有參數的裝飾器
def FuncNoArgDecrator(func):
def wrapper():
print "函數沒有參數的裝飾器"
func()
return wrapper

#函數有參數的裝飾器
def FuncArgDecrator(func):
def wrapper(arg):
print "函數有參數的裝飾器"
func(arg)
return wrapper

#函數有返回值的裝飾器
def FuncReturnDecrator(func):
def wrapper():
print "函數有返回值的裝飾器"
result=func()
return result
return wrapper

#這兩個函數用
def login():
print '開始登錄'

def logout():
print '退出登錄'

@FuncArgDecrator
def Lee(arg):
print 'I am %s' %arg

@FuncNoArgDecrator
def Marlon():
print 'i am Marlon'

@DecratorArgFuncNoArg(login,logout)
def Allen():
print 'i am Allen'

@DecratorArgFuncArg(login,logout)
def Aswill(name):
print 'I am %s' %name

@FuncReturnDecrator
def Frank():
return 'I am frank'

if __name__=='__main__':
SeparatorLine()
Lee('Lee')
SeparatorLine()
Marlon()
SeparatorLine()
Allen()
SeparatorLine()
Aswill('Aswill')
SeparatorLine()
result = Frank()
print result

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved