python装饰器作业

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python装饰器作业相关的知识,希望对你有一定的参考价值。

# user_dic={‘xiaohong‘:‘123‘,‘xiaobai‘:‘123‘,‘xiaohei‘:‘123‘}
# with open(‘idpd.txt‘,‘w‘,encoding=‘utf-8‘) as f:
#     f.write(str(user_dic))
# with open(‘idpd.txt‘,‘r‘,encoding=‘utf-8‘) as f2:
#     read=f2.read()
#     print(read)
#     user_dic=eval(read)
#将user_dic字典写入文件,以及将文件字典导入
# idpd_path=r‘F:\Pycharmprojects\0615\idpd.txt‘
# idpd_dic={‘id‘:False,‘password‘:False}
# def Login(func):
#     def login(*args,**kwargs):
#         if idpd_dic[‘id‘] and idpd_dic[‘password‘]:
#             res=func(*args,**kwargs)
#             return res
#         with open(idpd_path,‘r‘,encoding=‘utf-8‘) as f:
#             login_dic=eval(f.read())
制作缓存
# from urllib.request import urlopen
# import os
# cashe_path=r‘F:\Pycharmprojects\0615\makecache.txt‘
# def make_cashe(func):
#     def wrapper(*args,**kwargs):
#         if os.path.getsize(cashe_path):
#             print(‘\033[45m====>有缓存\033[0m‘)
#             with open(cashe_path, ‘rb‘, ) as f:
#                 res=f.read()
#         else:
#             res=func(*args,**kwargs)
#             with open(cashe_path,‘wb‘) as f:A
#                 f.write(res)
#         return res
#     return wrapper
# @make_cashe
# def get(url):
#     return urlopen(url).read()

 


#在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
# fun_dic={}
# def Outer(key):
#     def outer(func):
#         def wrapper(*args,**kwargs):
#             fun_dic[key]=func
#         return wrapper
#     return outer
# 
# @Outer(‘f1‘)
# def f1():
#     print(‘from f1‘)
# @Outer(‘f2‘)
# def f2():
#     print(‘from f2‘)
# @Outer(‘f3‘)
# def f3():
#     print(‘fromt f3‘)
# f1()
# f2()
# f3()
# print(fun_dic)

 


#             i=input(‘id:‘)
#             password=input(‘password:‘)
#         if i in login_dic and password in login_dic:
#             print(‘login successfully‘)
#             idpd_dic[‘id‘]=True
#             idpd_dic[‘password‘]=True
#             res=func(*args,**kwargs)
#             return res
#         else:
#             print(‘login error‘)
#     return login
#认证成功后,之后多次运行其他不再需要认证
#在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
# fun_dic={}
# def Outer(key):
#     def outer(func):
#         def wrapper(*args,**kwargs):
#             fun_dic[key]=func
#         return wrapper
#     return outer
# 
# @Outer(‘f1‘)
# def f1():
#     print(‘from f1‘)
# @Outer(‘f2‘)
# def f2():
#     print(‘from f2‘)
# @Outer(‘f3‘)
# def f3():
#     print(‘fromt f3‘)
# f1()
# f2()
# f3()
# print(fun_dic)

 

以上是关于python装饰器作业的主要内容,如果未能解决你的问题,请参考以下文章

python之闭包函数 装饰器 作业

Python 迭代器&生成器,装饰器,递归,算法基础:二分查找二维数组转换,正则表达式,作业:计算器开发

Python面向对象学习之八,装饰器

python学习笔记之装饰器(语法糖)

python学习笔记第八节(函数的相关作业)

python学习第十一天 装饰器