# Author: 刘佳赐-Isabelle
# Email: jiaci.liu@gmail.com
'''
练习题:
1、整理装饰器的形成过程,背诵装饰器的固定格式
2、编写装饰器,在每次执行被装饰函数之前打印一句’每次执行被装饰函数之前都得先经过这里,这里根据需求添加代码’
3、编写装饰器,在每次执行被装饰函数之后打印一句’每次执行完被装饰函数之后都得先经过这里,这里根据需求添加代码’
4、编写装饰器,在每次执行被装饰函数之前让用户输入用户名,密码,给用户三次机会,登录成功之后,才能访问该函数.
5、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,只支持单用户的账号密码,给用户三次机会),要求登录成功一次,后续的函数都无需再输入用户名和密码
6、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,可支持多账号密码),要求登录成功一次(给三次机会),后续的函数都无需再输入用户名和密码。
7、给每个函数写一个记录日志的功能, '''
'''
1、整理装饰器的形成过程,背诵装饰器的固定格式
'''
# def wrapper(f):
# def inner(*args, **kwargs):
# ret = f(*args, **kwargs)
# return ret
# return inner '''
2、编写装饰器,在每次执行被装饰函数之前打印一句’每次执行被装饰函数之前都得先经过这里,这里根据需求添加代码’
'''
# def wrapper2(f):
# def inner2(*args, **kwargs):
# print('每次执行被装饰函数之前都得先经过这里,这里根据需求添加代码')
# ret = f(*args, **kwargs)
# return ret
# return inner2 '''
3、编写装饰器,在每次执行被装饰函数之后打印一句’每次执行完被装饰函数之后都得先经过这里,这里根据需求添加代码’
'''
# def wrapper3(f):
# def inner(*args, **kwargs):
# ret = f(*args, **kwargs)
# print('每次执行完被装饰函数之后都得先经过这里,这里根据需求添加代码')
# return ret
# return inner '''
4、编写装饰器,在每次执行被装饰函数之前让用户输入用户名,密码,给用户三次机会,登录成功之后,才能访问该函数.
'''
# # Method 1
# def wrapper41(f):
# def inner(*args, **kwargs):
# '''
# Function to check user name and password
# :param args:
# :param kwargs:
# :return:
# '''
# userinfo = []
# username_list = []
# with open('jd_userinfo', encoding='utf-8') as file:
# for line in file:
# username_list.append(line.strip().split('|')[0])
# userinfo.append(line.strip().split('|'))
#
# username = input('Please input your username:').strip()
#
# if username in username_list:
# password = input('Please input your password:').strip()
# for times in range(0, 3):
# if [username, password] in userinfo and times < 2:
# ret = f(*args, **kwargs)
# return ret
# elif [username, password] not in userinfo and times < 2:
# times += 1
# print('Invalid Password, left %d times!' % (3-times))
# password =input('Please input your password again:').strip()
# elif [username, password] not in userinfo and times >= 2:
# print('Invalid Password, tried 3 times, your account has been locked!!')
# elif username not in username_list:
# print('Invalid username!')
# return inner
#
# # Method 2
# def wrapper42(f):
# def inner(*args, **kwargs):
# times = 0 # tried times
# userinfo = []
# username_list = []
# with open('jd_userinfo', encoding='utf-8') as file:
# for line in file:
# username_list.append(line.strip().split('|')[0])
# userinfo.append(line.strip().split('|'))
#
# username = input('Please input your username:').strip()
#
# if username in username_list:
# password = input('Please input your password:').strip()
# while 1:
# if [username, password] in userinfo and times < 2:
# ret = f(*args, **kwargs)
# return ret
# elif [username, password] not in userinfo and times < 2:
# times += 1
# print('Invalid Password, left %d times!' % (3-times))
# password =input('Please input your password again:').strip()
# elif [username, password] not in userinfo and times >= 2:
# print('Invalid Password, tried 3 times, your account has been locked!!')
# break
#
# elif username not in username_list:
# print('Invalid username!')
# return inner
#
# @wrapper41
# # @wrapper42
# def f():
# print(111)
#
# f() '''
5、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,只支持单用户的账号密码,给用户三次机会),
要求登录成功一次,后续的函数都无需再输入用户名和密码
''' # login_status = {
# 'username': None,
# 'status': False,
# }
#
# def wrapper(f):
# def inner(*args, **kwargs):
# '''
# Function to check login status, if not logged in, check user name and password to login;
# once logged in, no need to verify status for further functions!
# :param args:
# :param kwargs:
# :return:
# '''
# if login_status['status']:
# ret = f(*args, **kwargs)
# return ret
# else:
# userinfo = []
# username_list = []
# with open('jd_userinfo', encoding='utf-8') as file:
# for line in file:
# username_list.append(line.strip().split('|')[0])
# userinfo.append(line.strip().split('|'))
#
# username = input('Please input your username:').strip()
#
# if username in username_list:
# password = input('Please input your password:').strip()
# for times in range(0, 3):
# if [username, password] in userinfo and times < 2:
# ret = f(*args, **kwargs)
# login_status['status'] = True
# login_status['username'] = username
# return ret
# elif [username, password] not in userinfo and times < 2:
# times += 1
# print('Invalid Password, left %d times!' % (3-times))
# password =input('Please input your password again:').strip()
# elif [username, password] not in userinfo and times >= 2:
# print('Invalid Password, tried 3 times, your account has been locked!!')
# elif username not in username_list:
# print('Invalid username!')
# return inner
#
# @wrapper
# def func1():
# print(111)
#
# @wrapper
# def func2():
# print(222)
#
# @wrapper
# def func3():
# print(333)
#
# func1()
# func2()
# func3() '''
6、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,可支持多账号密码),
要求登录成功一次(给三次机会),后续的函数都无需再输入用户名和密码。
''' # login_status = {
# 'TM_username': None,
# 'TM_status': False,
# 'JD_username': None,
# 'JD_status': False,
# }
#
#
# def account(Flag):
# def wrapper(f):
# def inner(*args, **kwargs):
# '''
# Function to check login status, if not logged in (available to check multiple accounts),
# check user name and password to login;
# once logged in, no need to verify status for further functions!
# :param args:
# :param kwargs:
# :return:
# '''
# account_book = Flag.lower()+'_userinfo'
# account_username = Flag+'_username'
# account_status = Flag+'_status'
#
# if login_status[account_status]:
# ret = f(*args, **kwargs)
# return ret
# else:
# userinfo = []
# username_list = []
#
# with open(account_book, encoding='utf-8') as file:
# for line in file:
# username_list.append(line.strip().split('|')[0])
# userinfo.append(line.strip().split('|'))
#
# username = input('Please input your %s account username:' % Flag).strip()
#
# if username in username_list:
# password = input('Please input your %s account password:' % Flag).strip()
# for times in range(0, 3):
# if [username, password] in userinfo and times < 2:
# login_status[account_status] = True
# login_status[account_username] = username
# ret = f(*args, **kwargs)
# return ret
# elif [username, password] not in userinfo and times < 2:
# times += 1
# print('Invalid Password, left %d times!' % (3-times))
# password =input('Please input your password again:').strip()
# elif [username, password] not in userinfo and times >= 2:
# print('Invalid Password, tried 3 times, your account has been locked!!')
# elif username not in username_list:
# print('Invalid username!')
# return inner
# return wrapper
#
# @account('TM')
# def func1():
# print(111)
#
# @account('JD')
# def func2():
# print(222)
# print(login_status['JD'+'_username'])
#
# @account('TM')
# def func3():
# print(333)
#
# func1()
# func2()
# func3() '''
7、给每个函数写一个记录日志的功能,
'''
# import time
# struct_time = time.localtime()
#
# def wrapper(f):
# def inner(*args, **kwargs):
# ret = f(*args, **kwargs)
# with open('diary', mode='a', encoding='utf-8') as file:
# file.write('Function {} was conducted at {}'.format(str(f)[10:str(f).index('at')-1],
# time.strftime("%Y-%m-%d %H:%M:%S", struct_time)))
# return ret
# return inner
#
# @wrapper
# def func():
# print(1)
#
# func() """
功能要求:每一次调用函数之前,要将函数名称,时间节点记录到log的日志中。
所需模块:
import time
struct_time = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S",struct_time))
1),启动程序,首页面应该显示成如下格式:
欢迎来到博客园首页
1:请登录
2:请注册
3:文章页面
4:日记页面
5:评论页面
6:收藏页面
7:注销
8:退出程序
2),用户输入选项,3~6选项必须在用户登录成功之后,才能访问成功。
3),用户选择登录,用户名密码从register文件中读取验证,三次机会,
没成功则结束整个程序运行,成功之后,可以选择访问3~6项,访问页面之前,
必须要在log文件中打印日志,日志格式为-->用户:xx 在xx年xx月xx日 执行了 %s函数,
访问页面时,页面内容为:欢迎xx用户访问评论(文章,日记,收藏)页面
4),如果用户没有注册,则可以选择注册,注册成功之后,可以自动完成登录,然后进入首页选择。
5),注销用户是指注销用户的登录状态,使其在访问任何页面时,必须重新登录。 """
# import time
# struct_time = time.localtime()
#
#
# login_status = {
# 'TM_username': None,
# 'TM_status': False,
# 'JD_username': None,
# 'JD_status': False,
# }
#
# default_page = '''
# 欢迎来到博客园首页
# 1:请登录
# 2:请注册
# 3:文章页面
# 4:日记页面
# 5:评论页面
# 6:收藏页面
# 7:注销
# 8:退出程序
# '''
# def account(Flag='TM'):
# def login_check(func):
# '''
# Decoration function
# :param func: function to be decorated
# :return: func
# '''
# def inner(*args, **kwargs):
# '''
# decoration function
# :param args:
# :param kwargs:
# :return: decorated function
# '''
# account_book = Flag.lower()+'_userinfo'
# account_username = Flag+'_username'
# account_status = Flag+'_status'
# account_diary = Flag+'_diary'
#
# if login_status[account_status]:
# ret = func(*args, **kwargs)
#
# with open(account_diary, mode='a', encoding='utf-8') as file:
# file.write('用户:{}在{}执行了{}\n'.format(login_status[account_username],
# time.strftime("%Y-%m-%d %H:%M:%S", struct_time),
# str(func)[10:str(func).index('at') - 1]))
# return ret
# else:
# print("Please login first!")
#
# # check user name and password
# username = input("Please input your username:").strip()
#
# # make a list of saved username and corresponding password
# # TODO: is this necessary to create a new list?
# username_list = [] # list of user name
# userinfo_list = [] # list of user name and corresponding password
# with open(account_book, encoding="utf-8") as file:
# for line in file:
# username_list.append(line.strip().split("|")[0]) # TODO:any simpler expression?
# userinfo_list.append(line.strip().split("|")) # TODO:any simpler expression?
# if username in username_list:
# password = input('Please input your password:').strip()
# for times in range(0, 3):
# if [username, password] in userinfo_list:
# login_status[account_username] = username
# login_status[account_status] = True
# ret = func(*args, **kwargs)
#
# with open(account_diary, mode='a', encoding='utf-8') as file:
# file.write('用户:{}在{}执行了{}\n'.format(login_status[account_username],
# time.strftime("%Y-%m-%d %H:%M:%S", struct_time),
# str(func)[10:str(func).index('at') - 1]))
# return ret
# elif [username, password] not in userinfo_list and times < 2:
# times += 1
# print('Invalid password, left %d times!' % (3 - times))
# password = input('Please input your password again:')
# elif [username, password] not in userinfo_list and times >= 2:
# print('Invalid password, failed for three times!! You account has been locked!')
# elif username not in username_list:
# print("Unregistered username, please register!")
# register()
# return inner
# return login_check
#
#
# @account('JD')
# def register():
# global operation
#
# # check whether the username is available (occupied or not)
# username_check = [] # TODO: is this necessary to create a new list?
#
# with open("jd_userinfo", "r+", encoding="utf-8") as file:
# for line in file:
# username_check.append(line.strip().split()[0])
# username = input("Please set your username:").strip()
# while 1:
# if username not in username_check:
# password = input("Please set your password:")
# file.write("{}|{}\n".format(username, password))
#
# login_status['JD'+'_status'] = True
# login_status['JD'+'_username'] = username
# print(default_page)
#
# with open('JD' + '_diary', mode='a', encoding='utf-8') as file2:
# file2.write('用户:{}在{}执行了{}\n'.format(login_status['JD' + '_username'],
# time.strftime("%Y-%m-%d %H:%M:%S", struct_time),
# str(register)[10:str(register).index('at') - 1]))
# operation = input('Please select your operation(1-8):')
# dic[int(operation)]()
#
# elif username in username_check:
# print("Username has been taken, please reset your username!!")
# username = input("Please set your username again:").strip()
#
# @account('JD')
# def login():
# print(default_page)
# operation = int(input('Please select your operation(1-8):'))
# if operation == 1:
# print('You have already logged in!!')
# operation = int(input('Please select your operation(2-8):'))
# else:
# dic[operation]()
#
#
# @account('JD')
# def page():
# print("欢迎用户%s访问文章页面" % login_status['JD'+'_username'])
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()
#
# @account('JD')
# def diary():
# print("欢迎用户%s访问日志页面" % login_status['JD'+'_username'])
# with open('JD'+'_diary', encoding='utf-8') as file:
# for line in file:
# print(line.strip('\n'))
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()
#
# @account('JD')
# def comment():
# print("欢迎用户%s访问评论页面" % login_status['JD'+'_username'])
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()
#
# @account('JD')
# def save():
# print("欢迎用户%s访问收藏页面" % login_status['JD'+'_username'])
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()
#
# @account('JD')
# def logout():
# print("账号已退出!")
#
# @account('JD')
# def quit_operation():
# pass
#
# dic = {
# 1: login,
# 2: register,
# 3: page,
# 4: diary,
# 5: comment,
# 6: save,
# 7: logout,
# 8: quit_operation,
# }
#
#
# if __name__ == '__main__':
# print(default_page)
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()

day04-decorator的更多相关文章

  1. 设计模式(三):“花瓶+鲜花”中的装饰者模式(Decorator Pattern)

    在前两篇博客中详细的介绍了"策略模式"和“观察者模式”,今天我们就通过花瓶与鲜花的例子来类比一下“装饰模式”(Decorator Pattern).在“装饰模式”中很好的提现了开放 ...

  2. 设计模式(九)装饰者模式(Decorator Pattern)

    一.引言 在软件开发中,我们经常想要对一类对象添加不同的功能,例如要给手机添加贴膜,手机挂件,手机外壳等,如果此时利用继承来实现的话,就需要定义无数的类,如StickerPhone(贴膜是手机类).A ...

  3. Python之美--Decorator深入详解

    转自:http://www.cnblogs.com/SeasonLee/archive/2010/04/24/1719444.html 一些往事 在正式进入Decorator话题之前,请允许我讲一个小 ...

  4. C#设计模式系列:装饰模式(Decorator)

    1. 装饰模式简介 装饰模式动态地给一个对象添加额外的职责.例如一幅画有没有画框都可以挂在墙上,画就是被装饰者.但是通常都是有画框的.在挂在墙上之前,画可以被蒙上玻璃,装到框子里,所以在画上加一层画框 ...

  5. 装饰模式 - Decorator 和 外观模式 - Facade

    装饰模式 Decorator,不改变接口但动态给对象加入责任,所需功能按顺序串联起来控制,比生成子类灵活. 外观模式 Facade,让接口更简单.为子系统中的一组接口提供一个一致的界面. 参考:

  6. 设计模式学习之路——Decorator装饰模式(结构模式)

    子类复子类,子类何其多 假如我们需要为游戏中开发一种坦克,除了各种不同型号的坦克外,我们还希望在不同场合中为其增加以下一种或多种功能:比如红外线夜视功能,比如水陆两栖功能,比如卫星定位功能等等. 动机 ...

  7. angular中自定义依赖注入的方法和decorator修饰

    自定义依赖注入的方法 1.factory('name',function () { return function(){ } }); 2.provider('name',function(){ thi ...

  8. python嵌套函数、闭包与decorator

    1 一段代码的执行结果不光取决与代码中的符号,更多地是取决于代码中符号的意义,而运行时的意义是由名字空间决定的.名字空间是在运行时由python虚拟机动态维护的,但是有时候我们希望能将名字空间静态化. ...

  9. [工作中的设计模式]装饰模式decorator

    一.模式解析 装饰模式又名包装(Wrapper)模式.装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案. 装饰模式的要点主要是: 1.需要对已有对象扩展新的功能,又不希望改变原有对 ...

  10. python 中的decorator

    python 中decorator的作用就是一个包装的作用,所谓包装指在执行真正的函数之前或者之后,我们可以有一些额外的发挥余地. decorator形式如下 def dec(arg1): print ...

随机推荐

  1. 小程序——微信小程序初学踩过的坑

    微信小程序初学踩过的坑 一.前言     最近因为某些需要和个人兴趣打算开发一下微信小程序,经过在官方网站上的基本了解,我大体知道了微信小程序开发的大致过程,其实最本质的就是MVVM,借用了很多模式上 ...

  2. 判断ORACLE启动时使用spfile还是pfile

    自Oracle 9i以后启动的时候默认使用的初始化文件是spfile,我们可以通过如下三种方式来判断是SPFILE还是PFILE方式启动数据库.1.show parameter spfile2.sho ...

  3. PHP中 array_map 与 array_column 之间的关系

    (PHP 5 >= 5.5.0) array_map()与array_column()用法如下: array_map();将回调函数作用到给定数组的单元上array_column();快速实现: ...

  4. 调整home和根分区大小

    目标:将VolGroup-lv_home缩小到100G,并将剩余的空间添加给VolGroup-lv_root ============================================= ...

  5. BZOJ2565:最长双回文串(Manacher)

    Description 顺序和逆序读起来完全一样的串叫做回文串.比如acbca是回文串,而abc不是(abc的顺序为“abc”,逆序为“cba”,不相同). 输入长度为n的串S,求S的最长双回文子串T ...

  6. linux常用搜索文件命令

    使用linux系统难免会忘记文件所在的位置,可以使用以下命令对系统中的文件进行搜索.搜索文件的命令为”find“:”locate“:”whereis“:”which“:”type“ 方法/步骤     ...

  7. docker-3-常用命令(中)

    容器命令 1.有镜像才能创建容器,这是根本前提(下载一个CentOS镜像演示) docker pull centos 2.新建并启动容器 docker run [OPTIONS] IMAGE [COM ...

  8. VC++和C语言中常见数据类型转换为字符串的方法

    1.短整型(int) itoa(i,temp,10);///将i转换为字符串放入temp中,最后一个数字表示十进制 itoa(i,temp,2); ///按二进制方式转换 2.长整型(long) lt ...

  9. [转] 各种Json解析工具比较 - json-lib/Jackson/Gson/FastJson

    JSON技术的调研报告 一 .各个JSON技术的简介和优劣1.json-libjson-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包,包括com ...

  10. IBAction作用相当于void,NSLog(@"被调用的方法名是%s",__func__);

    IBAction作用相当于void,NSLog(@"被调用的方法名是%s",__func__);