函数练习题
练习题
一:编写3个函数,每个函数执行的时间是不一样的,
提示:可以使用time.sleep(2),让程序sleep 2s或更多,
import time
def test1():
time.sleep(1)
print("test1")
def test2():
time.sleep(2)
print("test2")
def test3():
time.sleep(3)
print("test3")
test1()
test2()
test3()
二:编写装饰器,为每个函数加上统计运行时间的功能
提示:在函数开始执行时加上start=time.time()就可纪录当前执行的时间戳,函数执行结束后在time.time() - start就可以拿到执行所用时间
import time
def outer(func):
def timmer():
start = time.time()
func()
stop = time.time()
take = stop-start
print("time is %s" %take)
return timmer
@outer
def test1():
time.sleep(1)
print("test1")
@outer
def test2():
time.sleep(2)
print("test2")
@outer
def test3():
time.sleep(3)
print("test3")
test1()
test2()
test3()
三:编写装饰器,为函数加上认证的功能,即要求认证成功后才能执行函数
import time
name = "nico"
passwd = "123"
def outer(func):
def timmer():
u_name = input("username:")
password = input("password:")
if u_name == name and password == passwd:
start = time.time()
func()
stop = time.time()
take = stop-start
print("time is %s" %take)
else:
print("wrong")
return timmer
@outer
def test1():
time.sleep(1)
print("test1")
@outer
def test2():
time.sleep(2)
print("test2")
@outer
def test3():
time.sleep(3)
print("test3")
test1()
test2()
test3()
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
提示:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
import time
flag = False
def login(name,passwd):
f = open("装饰器练习1","r",encoding="utf-8")
data = f.readlines()
for i in data:
i.strip()
msg = eval(i)
if name == msg["name"] and passwd == msg["password"]:
global flag
flag = True
def outer(func):
def timmer():
if not flag:
name = input("username:")
passw = input("password:")
login(name,passw)
if flag:
start = time.time()
func()
stop = time.time()
take = stop-start
print("time is %s" %take)
else:
print("wrong")
return timmer
@outer
def test1():
time.sleep(1)
print("test1")
@outer
def test2():
time.sleep(2)
print("test2")
@outer
def test3():
time.sleep(3)
print("test3")
test1()
test2()
test3()

浙公网安备 33010602011771号