python 扩展注册功能装饰器举例

db_path='db.txt'
def get_uname():
    while True:
        uname=input('请输入用户名:').strip()
        if uname.isalpha():
            with open(r'%s' %(db_path),'r',encoding='utf-8') as f:
                for i in f:
                    unifo=i.strip('\n').split(',')
                    print (unifo)   #查看查找过程
                    if uname==unifo[0]:
                        print('用户已存在,请重新输入')
                        break
                else:
                    return uname
        else:
            print ('用户名必须是中文或字母')
def get_pwd():
    while True:
        pwd1=input('请输入密码:').strip()
        pwd2=input('请再次输入密码:').strip()
        if pwd1 == pwd2:
            return pwd1
        else:
            print('两次输入的密码不一致,请重新输入...')
def get_bal():
    while True:
        bal=input('请输入余额:')
        if bal.isdecimal():
            return bal
        else:
            print ('钱是数字,傻逼 。。。')
def file_hanle(uname, pwd, bal):
     with open(r'%s' %(db_path),'a',encoding='utf-8') as f:
         f.write('%s,%s,%s\n' %(uname, pwd, bal))
def register():
    uname = get_uname()  # 拿到合法的用户名
    pwd = get_pwd()  # 拿到合法的密码
    bal = get_bal()  # 拿到合法的余额
    file_hanle(uname, pwd, bal)  # 写入文件
#===============================================装饰器
def example(func):
    def wrapper(*args,**kwargs):
        start_time = time.time()      #可扩展功能
        res = func(*args, **kwargs)
        stop_time = time.time()
        print(stop_time - start_time)
        return res
    return wrapper
register=example(register)
#=====================================
res=register()
print (res)
posted @ 2019-06-09 17:30  small_white-  阅读(590)  评论(0编辑  收藏  举报