目录
1、编写课上讲解的有参装饰器准备明天默写
def auth(login_type): def outter(func): def warpper(*args,**kwargs): func(*args,**kwargs) if login_type=="mysql": print("基于数据库") elif login_type=="file": print("基于文件") return warpper return outter @auth("mysql") def my_mysql(): print("我是数据库函数") @auth("file") def my_file(): print("我是文件函数") my_mysql() my_file()
2、在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
d = {} count = -1 def d_append(func): def warpper(): global count count += 1 func() d[count]=[func.__name__,func] return warpper @d_append def index(): print("我是主页") @d_append def footer(): print("我是尾页") index() footer()
3、编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
import time def timmer(func): def warpper(*args,**kwargs): func(*args,**kwargs) file_path = input("请输入文件路径:") with open(f"{file_path}","a",encoding="utf-8") as f : f.write(time.strftime(f'%Y-%m-%d %X {func.__name__} run\n')) return warpper @timmer def f1(): print("我是f1") @timmer def f2(): print("我是f2") f1() f2()
4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
str1 = "hzisdsb" list1 = [1,2,3,4] dict1 = {"a":1,"b":2} set1 = {1,2,3} tuple1 = (1,2,3,) def my_for(type,count=0): iteration = type.__iter__() while count<len(type): print(iteration.__next__()) count+=1 my_for(str1) my_for(list1) my_for(dict1) my_for(set1) my_for(tuple1) with open("a.txt","r",encoding="utf-8")as f : while True: try: print(f.__next__()) except StopIteration: break
5、自定义迭代器实现range功能
def my_rang(start,stop,step=1): while start<stop: yield start start+=step res = my_rang(1,100,1) print(res.__next__()) print(res.__next__()) print(res.__next__())
来源:https://www.cnblogs.com/hz2lxt/p/12561679.html