当前位置:网站首页>How to simplify a lot of if... Elif... Else code?
How to simplify a lot of if... Elif... Else code?
2022-06-11 17:22:00 【Python Programming Jacko】
In everyday code , We always face a lot of if…elif…else The problem of conditional branch selection . Tell the truth , In most cases, my first recommendation is to write honestly
if…elif, And try to extract the content under each branch into independent functions . The structure is clear , Intention understanding , It is very convenient for writing and reading . however , In some special circumstances , You can also use other more elegant ways , Like we shared before 《 Don't use
if-elif sentence , How to judge the rank of a number gracefully ?》, And this article to share today , You can broaden your thinking of coding .
In today's Github read EdgeDB[1] Code for , Found it dealing with a lot of if…elif…else When judging , Using a very clever decorator . Let's see what this method is .
Today is double eleven , Suppose we want to do a function , Judge the discount he can get according to the user's level . The conventional if … elif… This is how it is written :
def get_discount(level):
if level == 1:
" A lot of calculation code "
discount = 0.1
elif level == 2:
" A lot of calculation code "
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 ' Wrong level '
return discount
Everybody knows , So many if … elif… The code is very ugly , It's hard to maintain . And each if There is a lot of code inside . This function will be pulled very long .
Some students know , You can use a dictionary to rewrite this too long if Judge :
def parse_level_1():
" A lot of calculation code "
discount = 0.1
return discount
def parse_level_2():
" A lot of calculation code "
discount = 0.2
return discount
def parse_level_3():
" A lot of calculation code "
discount = 0.3
return discount
def parse_level_4():
" A lot of calculation code "
discount = 0.4
return discount
def parse_level_5():
" A lot of calculation code "
discount = 0.5
return discount
def parse_level_6():
" A lot of calculation code "
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, ' Wrong level ')
But the method I learned today , It's easier than using a dictionary . Let's first look at its effect :
@value_dispatch
def get_discount(level):
return ' Wrong level '
@get_discount.register(1)
def parse_level_1(level):
" A lot of calculation code "
discount = 0.1
return discount
@get_discount.register(2)
def parse_level_2(level):
" A lot of calculation code "
discount = 0.2
return discount
@get_discount.register(3)
def parse_level_3(level):
" A lot of calculation code "
discount = 0.3
return discount
@get_discount.register(4)
def parse_level_4(level):
" A lot of calculation code "
discount = 0.4
return discount
@get_discount.register(5)
def parse_level_5(level):
" A lot of calculation code "
discount = 0.5
return discount
@get_discount.register(6)
def parse_level_1(level):
" A lot of calculation code "
discount = 3 + 2 - 5 * 0.1
return discount
discount = get_discount(3)
print(f' Grade 3 Users of , The discount received is :{discount}')
The operation effect is shown in the figure below :

Write it like this , More intuitive than using a dictionary , It's better than using it directly if … elif… More concise .
that , This decorator value_dispatch How to achieve it ? The password is hidden in this open source project EdgeDB Of Source code [2] in , The core code is just 20 Multiple lines :

also , It can also implement or query . For example, the user level is 2 perhaps 3 When , Discounts are 0.2, Then the code can be written as :
@get_discount.register(2)
@get_discount.register(3)
def parse_level_2(level):
" A lot of calculation code "
discount = 0.2
return discount
The operation effect is shown in the figure below :

Its code can only implement equal queries at present . But in fact, as long as the code is slightly modified , We can achieve greater than 、 Less than 、 Greater than or equal to 、 Less than or equal to 、 It's not equal to 、in Wait, judge . If you are interested , Please leave a message at the bottom of the article , Let's talk about how to modify this code tomorrow , Realize more logical judgment .
Push inside the post 、 Exchange of learning
We need a lot of front-end jobs 、python Position 、Java Position 、Android and iOS Development position of , Workplace : Beijing byte , Welcome to the school recruitment agency to scan the QR code below Look for me to push inside
Python Information 、 technology 、 Course 、 answer 、 For consultation, you can also directly click on the business card below ,
Add official customer service Qi↓
边栏推荐
- 信息安全数学基础 Chapter 1——整除
- 信息安全数学基础 Chapter 3——有限域(一)
- sql server中关于FORCESCAN的使用以及注意项
- What subclasses inherit, polymorphism, and upward transformation
- Analyze which should be tested in PMP and ACP with actual cases? Which is more useful?
- Report on the operation situation and future prospects of China's gear oil industry (2022-2028)
- 字符串转数值
- RecyclerView缓存复用解析,源码解读
- LeetCode-1005. K 次取反后最大化的数组和
- 我的CのERROR们
猜你喜欢
![[Clickhouse column] create a new library, user and role](/img/e5/d11493a37e25b7dde6cc43b3828749.png)
[Clickhouse column] create a new library, user and role

JINTE NET基金会将通过线上直播参与维度链全球战略发布会

Derivation of child numbering formula for nodes numbered I in full k-ary tree

A set of ThinkPHP wechat applet mall source code with background management

GUI guess number game, directly open play

Analysis report on sales status and supply and demand prospects of phosphoric acid fuel cell industry in the world and China 2022-2028 Edition

Authing biweekly news: authing forum launched (4.25-5.8)

Song of the sea in 5g Era

一套ThinkPHP微信小程序商城源码带后台管理

vscode保存代码时自动eslint格式化
随机推荐
which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mod
^32 execution context stack interview questions
Authoring share | understanding saml2 protocol
如何成为一个乐观派组织?
Environment configuration and pymysql installation
SQL injection attack under seed emulator (including SQL environment configuration)
LeetCode-859. Intimate string
Docker installs mysql5.7 (enable binlog function and modify characters)
A set of ThinkPHP wechat applet mall source code with background management
Characteristics of interfaces & comparison between interfaces and abstract classes
ASP. Net education OA system source code education industry OA system source code with document
What products are good for cross-border e-commerce? What are the top selling categories?
LeetCode-384. 打乱数组
Vscode configures eslint to automatically format with an error "the setting is deprecated. use editor.codeactionsonsave instead with a source“
Is the stock account recommended by qiniu safe? Is it reliable
满k叉树编号为 i 的节点的孩子编号公式推导
Dynamic: capturing network dynamics using dynamic graph representation learning
通过Xshell连接有跳板机/堡垒机的服务器
Analysis report on sales status and supply and demand prospects of phosphoric acid fuel cell industry in the world and China 2022-2028 Edition
【clickhouse专栏】新建库、用户及角色