No zuo no die...
如上例所示,show函数本身只有一个print语句,而使用装饰器以后,就变成了三个print,这里的print可以改成任何其它的语句,这就是函数的装饰器。
带参数的func(被装饰的函数):
In [22]: def decorative(func):
...: def wrapper(x):
...: print "Please say something...>"
...: func(x)
...: print "no zuo no die..."
...: return wrapper
...:
In [23]: @decorative
...: def show(x):
...: print x
...:
In [24]: show("hello,mars.")
Please say something...>
hello,mars.
no zuo no die...
现在我们来写一个简单的为函数添加执行时间的装饰器函数:
import time
def timmer(func):
def wrapper(*args,**kwargs):
start_time = time.time()
a = func()
stop_time = time.time()
print('The func run time is %s'% (stop_time-start_time))
return a
return wrapper
@timmer
def foo():
time.sleep(3)
print('in the foo')
print(foo())
接下来再写一个现实生活中能用得到的:
需求如下:
假定有三个页面,现在要实现其中2个页面验证登录之后才能访问,另一个页面不用验证即可访问
首先定义三个页面函数:
def index():
print('Welcome to index page')
return 'from index page'
def home():
print('Welcome to home page')
return 'from home page'
def bbs():
print('Welcome to bbs page')
return 'from bbs page'
然后定义装饰器函数:
user = sean
passwd = abc123
def auth(auth_type='local'):
def out_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type == 'local':
username == input('Username: ').strip()
password == input('Password: ').strip()
if user == username and passwd == password:
print('authentication passed')
func()
elif auth_type == 'ldap':
print('This is ldap authentication')
func()
return wrapper
return out_wrapper
接下来将装饰器分别应用于home函数与bbs函数:
def index():
print('Welcome to index page')