任意定义⼀个函数给其添加装饰器
要求:每次执⾏该函数,装饰器⾃动记录次数,记录需保存在⽂件中
以下代码可以实现装饰器⾃动记录次数,但不保存入文件
count = 0
def inner(func):
def wrapper(*args,**kwargs):
global count
res=func(*args,**kwargs)
count+=1
print(count)
return res
return wrapper
l=[15,1,54,0,56,52,3,46,23,20,5]
@inner
def find(l,k):
l.sort
i=len(l)//2
if l[i]==k:
print("找到了")
elif l[i]>k:
find(l[i:len(l)+1],k)
elif l[i]<k:
find(l[0:len(l)],k)
find(l,20)
可以实现写入文件,但是无法将文件中的数值拿出来运算
count = 0
def inner(func):
def wrapper(*args,**kwargs):
global count
res=func(*args,**kwargs)
# with open('a.txt', 'w+', encoding='utf-8') as f:
# count=count+1
# f.write(count)
with open('a.txt', 'w', encoding='utf-8') as f:
count = count + 1
f.write(str(count))
#print(count)
return res
return wrapper
l=[15,1,54,0,56,52,3,46,23,20,5]
@inner
#二分查找法
def find(l,k):
l.sort
i=len(l)//2
if l[i]==k:
print("找到了")
elif l[i]>k:
find(l[i:len(l)+1],k)
elif l[i]<k:
find(l[0:len(l)],k)
find(l,20)
'''
c=0
with open('a.txt','r+', encoding='utf-8') as f:
print(f.read())
str_c=f.read().strip()
# c=int(f.read().strip())+1
c=int(str_c)
c+=1
f.write(str(c))
print(c)
'''
网友评论