标签:index 本质 UNC 结果 附加 outer port local 修改
为其他函数添加附加功能
不能修改被装饰函数的调用方式
嵌套函数
高阶函数 + 嵌套函数 = 装饰器
# Author:Li Dongfei
import time
def bar():
time.sleep(3)
print("in the bar")
def test1(func):
start_time = time.time()
func()
stop_time = time.time()
print("the func run time is %s" %(stop_time - start_time))
test1(bar)
# Author:Li Dongfei
import time
def bar():
time.sleep(3)
print("in the bar")
def test2(func):
print(func)
return func
bar = test2(bar)
bar()
# Author:Li Dongfei
def foo():
print("in the foo")
def bar():
print("in the bar")
bar()
foo()
# Author:Li Dongfei
import time
def timer(func): #func == test1的内存地址
def deco():
start_time = time.time()
func() #run test1()
stop_time = time.time()
print("the func run time is %s" %(stop_time - start_time))
return deco
def test1():
time.sleep(3)
print("in the test1")
def test2():
time.sleep(3)
print("in the test2")
test1 = timer(test1)
test1()
# Author:Li Dongfei
import time
def timer(func): #func == test1的内存地址
def deco():
start_time = time.time()
func() #run test1()
stop_time = time.time()
print("the func run time is %s" %(stop_time - start_time))
return deco
@timer # test1 = timer(test1)
def test1():
time.sleep(3)
print("in the test1")
@timer
def test2():
time.sleep(3)
print("in the test2")
test1()
test2()
# Author:Li Dongfei
import time
def timer(func):
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print("the func run time is %s" %(stop_time - start_time))
return deco
@timer
def test1():
time.sleep(1)
print("in the test1")
@timer #test2 = timer(test2) = deco , test2(name) == deco(name)
def test2(name):
time.sleep(2)
print("test2:",name)
test1()
test2("dongfei")
# Author:Li Dongfei
import time
user,passwd = 'dongfei','123456'
def auth(auth_type):
def outer_wrapper(func):
def wrapper(*args,**kwargs):
username = input("Username: ").strip()
password = input("Password: ").strip()
if auth_type == "local":
if user == username and passwd == password:
print("login successful")
res = func(*args,**kwargs)
return res #返回被装饰函数的执行结果
else:
exit("login failure")
elif auth_type == "ldap":
print("ldap认证")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") # home = wrapper()
def home():
print("welcome to home page")
return "from home"
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")
index()
print(home())
bbs()
标签:index 本质 UNC 结果 附加 outer port local 修改
原文地址:https://www.cnblogs.com/L-dongf/p/9874072.html