# 再见 if…elif… ，使用 Python 装饰器轻松拿下

def get_discount(level):
if level == 1:
"大量计算代码"
discount = 0.1
elif level == 2:
"大量计算代码"
discount = 0.2
elif level == 3:
discount = 0.3
elif level == 4:
discount = 0.4
elif level == 5:
discount = 0.5
elif level == 6:
discount = 3 + 2 - 5 * 0.1
else:
return '等级错误'
return discount

def parse_level_1():
"大量计算代码"
discount = 0.1
return discount

def parse_level_2():
"大量计算代码"
discount = 0.2
return discount

def parse_level_3():
"大量计算代码"
discount = 0.3
return discount

def parse_level_4():
"大量计算代码"
discount = 0.4
return discount

def parse_level_5():
"大量计算代码"
discount = 0.5
return discount

def parse_level_6():
"大量计算代码"
discount = 3 + 2 - 5 * 0.1
return discount

discount_map = {
1: parse_level_1,
2: parse_level_2,
3: parse_level_3,
4: parse_level_4,
5: parse_level_5,
6: parse_level_6,
}

discount = discount_map.get(level, '等级错误')

@value_dispatch
def get_discount(level):
return '等级错误'

@get_discount.register(1)
def parse_level_1(level):
"大量计算代码"
discount = 0.1
return discount

@get_discount.register(2)
def parse_level_2(level):
"大量计算代码"
discount = 0.2
return discount

@get_discount.register(3)
def parse_level_3(level):
"大量计算代码"
discount = 0.3
return discount

@get_discount.register(4)
def parse_level_4(level):
"大量计算代码"
discount = 0.4
return discount

@get_discount.register(5)
def parse_level_5(level):
"大量计算代码"
discount = 0.5
return discount

@get_discount.register(6)
def parse_level_1(level):
"大量计算代码"
discount = 3 + 2 - 5 * 0.1
return discount

discount = get_discount(3)
print(f'等级3的用户，获得的折扣是：{discount}')

@get_discount.register(2)
@get_discount.register(3)
def parse_level_2(level):
"大量计算代码"
discount = 0.2
return discount

[1] EdgeDB: https://github.com/edgedb/edgedb

[2] 源代码: https://github.com/edgedb/edged

• 6
点赞
• 5
评论
• 24
收藏
• 打赏
• 扫一扫，分享海报

11-26 39

12-07 66

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。