【python 】装饰器 (多个参数的函数,带参数的装饰器)【转】

最简单的模板是这样的

 #-*-coding:utf-8-*-

 def outer(func):
def inner():
print 'before'
func()
print 'after'
# return r
return inner
'''
def outer_1(func):
def inner():
print 'before 11'
func()
print 'after 22'
# return r
return inner @outer_1
'''
@outer
def F1():
print 'test' if __name__ == '__main__':
F1()
'''
运行结果
before
test
after
[Finished in 0.1s]
'''

函数带多个参数,装饰器对应修改以适合多种情况

# -*- coding: utf-8 -*-

from time import ctime
from time import sleep def ftfunc(func):
def timef(*s,**gs):
print "[%s] %s() called" % (ctime(),func.__name__)
return func(*s,**gs)
return timef @ftfunc
def foo(*s,**gs):
print(s)
print(gs) if __name__ == '__main__':
foo()
foo(1)
foo(1,2)
foo(1,2,3)
stu = {'name' : 'alam' ,'age' :12}
foo(1,2,3,**stu)
'''
运行结果
[Wed Jun 14 15:49:55 2017] foo() called
()
{}
[Wed Jun 14 15:49:55 2017] foo() called
(1,)
{}
[Wed Jun 14 15:49:55 2017] foo() called
(1, 2)
{}
[Wed Jun 14 15:49:55 2017] foo() called
(1, 2, 3)
{}
[Wed Jun 14 15:49:55 2017] foo() called
(1, 2, 3)
{'age': 12, 'name': 'alam'}
[Finished in 0.1s] '''

函数带多个参数,装饰器也带多个参数

# -*- coding: utf-8 -*-

def decrator(*dargs, **dkargs):
def wrapper(func):
def _wrapper(*args, **kargs):
print "decrator param:", dargs, dkargs
print "function param:", args, kargs
return func(*args, **kargs)
return _wrapper
return wrapper @decrator(1, a=2)
def foo(x, y=0):
print "foo", x, y if __name__ == '__main__':
foo(3, 4) '''
执行结果
decrator param: (1,) {'a': 2}
function param: (3, 4) {}
foo 3 4
[Finished in 0.1s]
'''

函数带多个参数,装饰器能转换参数类型

 # -*- coding: utf-8 -*-

 def validate(**vkargs):
def decorator(func):
def wrapper(**kargs):
for key in vkargs:
# 根据vkargs中的参数的类型对kargs的参数进行类型转换
kargs[key] = vkargs[key](kargs[key])
return func(**kargs)
return wrapper
return decorator @validate(x=int, y=float, z=float)
def move(x, y, z):
print "move %d (%0.2f, %0.2f)"%(x, y, z) if __name__ == '__main__':
move(x="", y="0.2", z="0.3")
'''
运行结果
move 1 (0.20, 0.30)
[Finished in 0.2s]
'''

一个简单的例子,登录页面

 # -*- coding: utf-8 -*-

 #模拟网站登陆访问认证

 name = 'abc'
password='' def certi(model):#装饰器
def outr(fun):#装饰器加参数需要多加一层嵌套
def login(*args,**kwargs):#为了兼容各类函数参数,添加 *args,**kwargs 不固定参数
if model=='password':
print('enter password')
user_name = raw_input('user_name ').strip()
paswd=raw_input('password ').strip()
if user_name==name and paswd==password:
print('pass')
return fun(*args,**kwargs)
else:
print('error ')
exit()
elif model=='lamp':
print('this is lamp')
return fun(*args,**kwargs)
else:
print('error')
return login
return outr def indxe():
print('home page !!') @certi(model='password')
def user():
print('user page !!') @certi(model='lamp')
def bbs(name):
print('bbs %s!!'%name) if __name__ == '__main__':
indxe()
user()
bbs(name='yjj')
'''
运行结果
home page !!
enter password
user_name abc
password 123
pass
user page !!
this is lamp
bbs yjj!!
'''
上一篇:nginx+uwsgi+django开发环境搭建


下一篇:head里两个重要标签base和meta