import os
import time
# 一:编写函数,(函数执行的时间是随机的),统计函数执行时间
def test():
start_time = time.time()
i = 0
while i < 10000:
i += 1
end_time = time.time()
print end_time - start_time
test()
# 二、编写装饰器,实现题1的功能,统计被装饰函数的执行时间
def decorator(func):
def Deco():
start_time = time.time()
func()
end_time = time.time()
print '程序执行时间为:',end_time - start_time
return Deco
@decorator
def test():
i = 0
while i < 1000000:
i += 1
print '完毕'
test()
# 三、编写装饰器,为函数加上认证的功能:如认证用户名、密码,通过才能调用函数
def decorator(func):
user_sourse = {'name_u':'lisen','password_u':123456}
def Dec():
name = raw_input('Enter user name:')
password = input('Enter password:')
if name == user_sourse['name_u']:
if password == user_sourse['password_u']:
print 'Login victory'
func()
else:
print 'Login faild'
return Dec
@decorator
def user():
print 'welcome to my word'
user()
# 四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
flag=False
def login(func):
def inner(*args,**kwargs):
global flag
while not flag:
name=raw_input('请输入用户名:')
pwd=raw_input('请输入密码:')
file_path = 'E:/Python/user.txt'
with open(file_path,'r') as f:
for line in f:
lst=line.strip().split('|')
if name==lst[0] and pwd==lst[1]:
print('登陆成功')
flag = True
while flag:
ret=func(*args,**kwargs)
return ret
return inner
@login
def name1():
print('你好吗?')
@login
def name2():
print('我还好')
# name1()
# name2()
# 九、编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,
# 日志文件路径可以指定,同时函数名也要写入
# 注意:时间格式的获取
# import time
# time.strftime('%Y-%m-%d %X')
import time
def decorator(func):
file_path = 'E:/Python/user1.txt'
def Dec():
with open(file_path,'a+') as f:
func()
res = '%s %s run\n'%(time.strftime('%Y-%m-%d %H:%M:%S'),func.__name__)
f.write(res)
return Dec
@ decorator
def f1():
print 'hello word'
# f1()
# f1()
装饰器
最新推荐文章于 2020-04-19 12:36:44 发布