# 巧妙使用Python装饰器处理if...elif...else

```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/edgedb/blob/master/edb/common/value_dispatch.py