b、返回值中包含函数名
[对装饰器的影响]:达到“不改变函数的调用方式“的效果
import time
def bar():
time.sleep(3)
print('in the bar')
def test2(func):
print('新添加的功能')
return func
bar=test2(bar)
bar()运行结果:
新添加的功能
in the bar
(3) 嵌套函数:在一个函数体内用def去声明一个新的函数(不是调用)
def foo():
print('in the foo')
def bar(): #声明一个新的函数,而不是调用函数
print('in the bar')
bar()
foo()运行结果:
in the foo
in the bar
4、装饰器的语法:高阶函数+嵌套函数=》装饰器 (下面的例子可以用pycharm的调试器调试一下,看看代码的运行顺序)
import time
def timer(func):
def deco(*args,**kwargs):#使用了不定参数
start_time=time.time()
res=func(*args,**kwargs) #运行函数
stop_time=time.time()
print('运行时间:',stop_time-start_time)
return res # 若无返回值,则返回None
return deco
@timer #等价于test1=timer(test1)=deco,即test1()=deco()
def test1():
time.sleep(3)
print('in the test1')
@timer #等价于test2=timer(test2)=deco,即test2(name)=deco(name)
def test2(name):
time.sleep(3)
print('in the test2',name)
test1()
print('-------------分界线------------------------')
test2('Tomwenxing')运行结果:
in the test1
运行时间: 3.00017197955322
-------------分界线------------------------
in the test2 Tomwenxing
运行时间: 3.000171422958374
5、带参数的装饰器
# -*- coding:utf-8 -*-
user,passwd='Tomwenxing','123'
#如装饰器带参数,一般是三层嵌套
def auth(auth_type): #第一层的参数是装饰器的参数
def outer_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('用户Tomwenxing已经成功登录!')
res = func(*args, **kwargs) #运行目标函数
return res
else:
exit('用户名或密码有错误')
elif auth_type=='ldap':
print('暂不支持这种登录方式!')
return wrapper
return outer_wrapper
def index():
print('欢迎来到index页面')
@auth(auth_type='local') #home=wrapper()
def home(name):
print('%s,欢迎来到home页面' %name)
return 'This is home page'
@auth(auth_type='ldap')
def bbs():
print('欢迎来到bbs页面 ')
index()
print('----------------------分界线-------------------')
print('函数的返回值为:',home('wenxing'))
print('----------------------分界线-------------------')
bbs()运行结果:
欢迎来到index页面
----------------------分界线-------------------
Username:Tomwenxing
Password:123
用户Tomwenxing已经成功登录!
wenxing,欢迎来到home页面
函数的返回值为: This is home page
----------------------分界线-------------------
暂不支持这种登录方式!
Copyright © 2019- xdyj.cn 版权所有
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务