装饰器
decrator
装饰器:
定义:本质是函数,(装饰其他函数)就是为其他函数添加功能
原则:1、不能修改被装饰的函数的源代码
2、不能修改被装饰的函数的调用方式
实现装饰器的功能知识储备
1、函数即变量
把函数当成参数传递给另一个函数
2、高阶函数(满足其一)
a:把一个函数名当做实参传递给另外一个函数(在不修改被装饰函数的源代码的情况下为
其他函数添加功能)
b:返回值中包含函数名(不修改函数的调用方式)
3、嵌套函数
在函数中又有函数
高阶函数+嵌套函数-》装饰器
参考:http://www.cnblogs.com/WhatTTEver/p/6680341.html
-----------------------------------------
#装饰器代码实现:
__author__ = "Alex Li"
import time
def timer(func): #timer(test1) func=test1
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs) #run test1()
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time))
return deco
@timer #test1=timer(test1) 返回了deco
def test1():
time.sleep(1)
print('in the test1')
@timer # test2 = timer(test2) = deco test2(name) =deco(name)
def test2(name,age):
print("test2:",name,age)
test1()
test2("alex",22)
-----------------------------------------
__author__ = "Alex Li"
import time
user,passwd = 'alex','abc123'
def auth(auth_type):
print("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("wrapper func args:", *args, **kwargs)
if auth_type == "local":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) # from home
print("---after authenticaion ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("搞毛线ldap,不会。。。。")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") # home=auth(auth_type)(func) 返回了 wrapper
def home(aa):
print("welcome to home page",aa)
return "from home"
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")
index()
print(home('surprised')) #wrapper()
bbs()
-----------------------------------------
其中 home=auth(auth_type)(func) 可以参考下面的代码
def a (name):
print (name)
def b(*args):
print('the args is %s'%(args))
def c():
print('the is c')
return 888
return b
print(a('li')('two dog'))
-----------------------------------------
def a (name):
print (name)
def b(*args):
print('the args is %s'%(args))
def c(**kwargs):
print('the is %s'%kwargs)
return 888
return c
return b
print(a('li')('two dong')(age=999))