函数及“变量”,将函数当作变量传入:
import time
def bar():
time.sleep(2)
print ("in the bar")
def test1(func):
start_time=time.time()
func() #run bar
stop_stime=time.time()
print ("the func run time is %s" %(stop_stime-start_time))
test1(bar)
in the bar
the func run time is 2.00496697426
实现装饰器:
1、函数及“变量”
2、高阶函数
a:把一个函数名当作实参传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
b:返回值中包含函数名(不修改函数的调用方式)
3、嵌套函数
高阶函数+嵌套函数=》装饰器
实例:
import time
#嵌套函数
def timer(func): #timer(test1) func=test1
#*args,**kwargs 这个代表不固定参数,可传参可不传参
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs)
stop_stime=time.time()
print ("the func run time is %s" %(stop_stime-start_time))
return deco
@timer #test1 = timer(test1)
def test1():
time.sleep(2)
print "in the test1"
@timer
def test2(name):
time.sleep(2)
print ("name:",name)
#下面操作相当于@timer,哪个函数用就在哪个函数前面加上@timer
# test1 = timer(test1)
# test1() #run deco()
# test2=timer(test2)
# test2()
test1()
test2("chao")
in the test1
the func run time is 2.00393605232
(‘name:’, ‘chao’)
the func run time is 2.00482201576
示例简单的网站验证登录:
#模拟登陆验证
user,passwd='chao','123'
def auth(auth_type): #auth_type: 'local'
print ("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type=="local":
username=raw_input("Username:").strip()
password=raw_input("Password:").strip()
if user==username and passwd==password:
print ("\033[32;1mUser has passed authentication\033[0m")
rex=func(*args,**kwargs)
# print ("--after")
return rex
else:
exit ("\033[31;1mInvalid username or password\033[0m")
elif auth_type=="ldap":
func(*args, **kwargs)
print ("这个没搞过")
return wrapper
return outer_wrapper
def index():
print ("welcome to index page")
@auth(auth_type="local") #home=auth()
def home():
print ("welcome to home page")
return "from home"
@auth(auth_type="ldap")
def bbs():
print ("welcome to bbs page")
index()
#run home()相当于执行wrapper
print (home())
bbs()
(‘auth func:’, ‘local’)
(‘auth func:’, ‘ldap’)
welcome to index page
Username:chao
Password:123
User has passed authentication
welcome to home page
from home
welcome to bbs page
这个没搞过