python_装饰器
装饰器是什么
装饰即修饰,意指为其他函数添加新功能
装饰器定义:本质就是函数,功能是为其他函数添加新功能
装饰器的原则
1.不修改被装饰函数的源代码(开放封闭原则)
2.为被装饰函数添加新功能后,不修改被修饰函数的调用方式
ps.装饰器=高阶函数+函数嵌套+闭包
高阶函数
高阶函数定义:
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
def foo(): print('我的函数名作为参数传给高阶函数') def gao_jie1(func): print('我就是高阶函数1,我接收的参数名是%s' %func) func() def gao_jie2(func): print('我就是高阶函数2,我的返回值是%s' %func) return func gao_jie1(foo) gao_jie2(foo) 高阶函数示范
#高阶函数应用2:把函数名当做参数传给高阶函数,高阶函数直接返回函数名 import time def foo(): print('from the foo') def timmer(func): start_time=time.time() return func stop_time=time.time() print('函数%s 运行时间是%s' %(func,stop_time-start_time)) foo=timmer(foo) foo() #总结:我们确实没有改变foo的调用方式,但是我们也没有为foo增加任何新功能 函数返回值是函数名
无参装饰器
无参装饰器=高级函数+函数嵌套
最基本的装饰器
#这就是一个实现一个装饰器最基本的架子 def timer(func): def wrapper(): func() return wrapper
装饰器的语法结构:
使用关键字 @
#高阶函数 加上闭包返回值:高阶函数就是不在原函数体上数据和调用结果,添加其他的功能
def timmer(func):
def warpper():
start_time = time.time() #开始时间
res = func() #这个的函数是调用的test()
stop_time = time.time() #结束时间
print('查看我运行的时间是:%s' %(stop_time-start_time))
return res
return warpper
@timmer #就等于是test=timmer(test) 不会改变test源代码
def test():
time.sleep(2)
print('我是test')
# print('我叫【%s】,我今年【%s】,我是【%s】'%(name,age,sex)
return "这是test的返回值"
# res = timmer(test)
# res
res = test()
print(res) #这个打印是打印的(return "这是test的返回值")
#####装饰器语法详解
import time
'''
@timmer #index = timmer(index)
index = timmer(index)
index()就等于---->返回的结果就是warper(),所以运行的就是warper()里面的代码。
'''
def timmer(x):
def warper():
start_time = time.time()
x()
stop_time = time.time()
print('运行的时间:%d'%(stop_time - start_time))
return warper
@timmer #index = timmer(index)
def index():
time.sleep(4)
print('from the index')
index()
装饰器:返回值、闭包、有参函数、高阶函数的结合
import time
current_dic = {'name':None,'login':False}
def timmer1(func):
def warper1(*args,**kwargs): #*args,**kwargs:可变长参数,
start_time = time.time()
res = func(*args,**kwargs)
# print(func(*args,**kwargs))
stop_time = time.time()
print('运行的时间:%d................................'%(stop_time - start_time))
return res
return warper1
def timmer2(acth_type = 'file'):
def timmer(func):
def warper(*args,**kwargs): # *args,**kwargs:可变长参数,
if acth_type == 'file':
if current_dic['name'] and current_dic['login']:
res = func(*args, **kwargs)
return res
username = input('username:')
password = input('password:')
if username == 'yang' and password == '123':
print('正确的.....')
current_dic['name'] = username # 将username的值赋给current_dic['username'],相当于永久保留
current_dic['login'] = True
start_time = time.time()
res = func(*args, **kwargs)
stop_time = time.time()
print('运行的时间:%d' % (stop_time - start_time))
return res
else:
print('输错了!!!!')
elif acth_type == 'sql':
print('还没学过,所以有问题.....')
return warper
return timmer
@timmer1
@timmer2(acth_type = 'file')
def acth(x,y):
time.sleep(3)
res = x if x > y else y
return res
@timmer2(acth_type = 'file') #index = timmer(index)
def index():
time.sleep(4)
print('from the index')
print('befor>>>>>',current_dic)
res = acth(1,2)
print(res)
index()
print('after>>>>',current_dic)
使用装饰器,添加新的功能,三次登陆
cuter_list = {'username':None,'login':False}
def three_land():
with open('old_user',encoding='utf-8') as f_read, \
open('locked','a+',encoding='utf-8') as f_write:
name_dic = {}
flag = True
res = False
count = 0
while flag and count <3:
f_read.seek(0)
f_write.seek(0)
count = 0
username = input('please input name:').strip()
for line in f_write:
if line.strip() == username:
print('用户已锁定,请联系管理员解锁')
break
else:
for line in f_read:
line =eval(line.strip())
if username == line['name']:
passwd = input('please input password:').strip()
if passwd == line['password']:
flag = False
res = True
break
else:
print('用户名或密码错误!')
if username in name_dic:
name_dic[username]+=1
else:
name_dic[username]=1
count =1
else:
if count == 0:
print('用户名不存在!')
for i in name_dic:
if name_dic[i] == 3:
count =3
f_write.write(username+'\n')
print('该用户3次登陆都未成功,已被锁定')
break
return res,username
def acth_type(type_ = 'flie'):
def acth(func):
def wrapper(*args,**kwargs):
if cuter_list['username'] and cuter_list['login']:
res = func(*args, **kwargs)
return res
if type_ == 'flie':
res_ture,username = three_land()
if res_ture:
cuter_list['username'] = username
cuter_list['login'] = True
res = func(*args, **kwargs)
return res
else:
print('验证错误......')
elif type_ == 'sql':
print('还没用过这种的文件......')
return wrapper
return acth
@acth_type(type_ = 'flie')
def login():
print('【last_one】登陆成功......')
@acth_type(type_ = 'flie')
def home(name):
print('【last_tow】%s 欢迎您进入主页'%name)
@acth_type(type_ = 'flie')
def shop():
print('【last_three】购物车中有:【%s】和【%s】和【%s】和【%s】'%('奶茶','面包','电脑','马云'))
print('befor>>>>>>>',cuter_list)
login()
home('yangxiang')
shop()
print('after>>>>>>>',cuter_list)

浙公网安备 33010602011771号