码迷,mamicode.com
首页 > 其他好文 > 详细

装饰器

时间:2019-06-11 01:07:41      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:api   username   choice   参数   inner   pre   *args   ice   append   

# athor : DevilsWhite
# -*- coding:UTF-8 -*-
account = {
"is_authenticated":False,
"username":"alex",
"password":"abc123"
}  #假装这个是数据库

vip_record = []
wallet = []

def login(func):  #父级函数名和要装饰参数函数
"""
账户登录认证
"""

def inner(*args,**kwargs):  #装饰器上
if account["is_authenticated"] == False: #查看是否需要认证 
username_input = input("Username>>>")
password_input = input("Password>>>")
if username_input == account["username"] and password_input == account["password"]:
account["is_authenticated"] = True
print("You‘re welcome, %s"%username_input)
func(*args,**kwargs)  #认证完毕后,执行目标函数即要装饰参数函数
else:print("username/password is worong".capitalize())
else:
print("You‘re welcome")
func(*args, **kwargs)
return inner  #装饰器下

def pay_money(func):
"""
目的是检测是否是会员和是否愿意充值
"""
def inner(*args,**kwargs):
while True:
if account["username"] in vip_record:
print("Hi,Vip~~ ",account["username"])
func(*args,**kwargs)
break
else:
choice = input("Do u want to be our Vip with 30$?(Y/N)")
if choice.upper() == "Y":
print("Your wallet is ",wallet[0])
if wallet[0] >= 30:
wallet[0] = wallet[0] - 30
vip_record.append(account["username"])
pass
else:
choice1 = input("Do u want to recharge your wallet?(Y/N)")
if choice1.upper() == "Y":
recharge = int(input("The num of money:"))
wallet[0] = recharge
elif choice1.upper() == "N":
print("Byebye~~")
pass
elif choice.upper() == "N":
print("Byebye~~")
pass
else:print("Please input right a choice~")
return inner



def home():
print("home".center(30,"-"))

@login  #语法糖,目的是偷懒
@pay_money
def America():
print("欧美专区".center(30,"-"))


def Japn():
print("日本专区".center(30,"-"))


def Korea(vip_level):
if vip_level > 3:
print("韩国专区".center(30, "-"))
else:pass

home()
America()

装饰器

标签:api   username   choice   参数   inner   pre   *args   ice   append   

原文地址:https://www.cnblogs.com/DevilsWhite/p/11001186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!