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)
相關文章
相關標籤/搜索