Python开发中如何优雅的处理多重if...elif...判断

2023-10-09 17:04

本文主要是介绍Python开发中如何优雅的处理多重if...elif...判断,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

回眸那年,懵懂的我以为学会了if判断,就能轻易判断世间所有逻辑进行处理。时至今日,我依然为我当年的想法所骄傲😂。工作中多重if...elif...经常会遇到,我也像如下的方式写了N+1次,内容如下:

use_standing = "diamond_user"if use_standing == "normal_user":  # 普通用户discount = 0.95# 大量的逻辑代码print("normal_user")
elif use_standing == "gold_user":  # 黄金用户discount = 0.9# 大量的逻辑代码print("gold_user")
elif use_standing == "platinum_user":  # 铂金用户discount = 0.85# 大量的逻辑代码print("platinum_user")
elif use_standing == "diamond_user":  # 钻石用户discount = 0.8# 大量的逻辑代码print("diamond_user")
elif use_standing == "starlight_user":  #  星耀用户discount = 0.7# 大量的逻辑代码print("starlight_user")
elif use_standing == "superior_user":  # 至尊用户discount = 0.6# 大量的逻辑代码print("superior_user")
else:print("The user type does not exist。")

通过判断不同的用户类型,进而针对不同的用户要进行大量的业务逻辑处理,这样的代码经常会有几百行乃至更多。慢慢的我开始厌烦这种代码,哪怕之前是我自己写的,过段时间再修改里面的业务逻辑我都很难受,更何况看到别人写这种,心里就只有MMP。

于是,以后再遇到多重判断逻辑必须优化。

方式1:使用字典的方式。

# 普通用户
def normal_user(type):"""大量的逻辑代码"""return type# 黄金用户
def gold_user(type):"""大量的逻辑代码"""return type# 铂金用户
def platinum_user(type):"""大量的逻辑代码"""return type# 钻石用户
def diamond_user(type):"""大量的逻辑代码"""return type# 星耀用户
def starlight_user(type):"""大量的逻辑代码"""return type# 至尊用户
def superior_user(type):"""大量的逻辑代码"""return typedef inexistence_user(type):return f"The user type {type} does not exist。"user_dict= {"normal_user": normal_user,"gold_user": gold_user,"platinum_user": platinum_user,"diamond_user": diamond_user,"starlight_user": starlight_user,"superior_user": superior_user,
}user_type = "platinum_user"
print(user_dict.get(user_type, inexistence_user)(user_type))

通过将不同的用户类型封装到不同的函数中,进而使用字典键值对获取调用。

方式2:使用EdgeDB中的轮子

代码地址:https://github.com/edgedb/edgedb/blob/master/edb/common/value_dispatch.py

我们直接拿来使用即可,示例如下:

源码文件名为value_dispatch.py,直接放在同目录或指定目录下调用就🆗!源码如下:

#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2021-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#from __future__ import annotations
from typing import *import functools
import inspect
import types_T = TypeVar("_T")class _ValueDispatchCallable(Generic[_T], Protocol):registry: types.MappingProxyType[Any, Callable[..., _T]]def register(self,val: Any,) -> Callable[[Callable[..., _T]], Callable[..., _T]]:...def register_for_all(self,val: Iterable[Any],) -> Callable[[Callable[..., _T]], Callable[..., _T]]:...def __call__(__self, *args: Any, **kwargs: Any) -> _T:...def value_dispatch(func: Callable[..., _T]) -> _ValueDispatchCallable[_T]:"""Like singledispatch() but dispatches by value of the first arg.Example:@value_dispatchdef eat(fruit):return f"I don't want a {fruit}..."@eat.register('apple')def _eat_apple(fruit):return "I love apples!"@eat.register('eggplant')@eat.register('squash')def _eat_what(fruit):return f"I didn't know {fruit} is a fruit!"An alternative to applying multuple `register` decorators is touse the `register_for_all` helper:@eat.register_for_all({'eggplant', 'squash'})def _eat_what(fruit):return f"I didn't know {fruit} is a fruit!""""registry: dict[Any, Callable[..., _T]] = {}@functools.wraps(func)def wrapper(arg0: Any, *args: Any, **kwargs: Any) -> _T:try:delegate = registry[arg0]except KeyError:passelse:return delegate(arg0, *args, **kwargs)return func(arg0, *args, **kwargs)def register(value: Any,) -> Callable[[Callable[..., _T]], Callable[..., _T]]:if inspect.isfunction(value):raise TypeError("value_dispatch.register() decorator requires a value")def wrap(func: Callable[..., _T]) -> Callable[..., _T]:if value in registry:raise ValueError(f'@value_dispatch: there is already a handler 'f'registered for {value!r}')registry[value] = funcreturn funcreturn wrapdef register_for_all(values: Iterable[Any],) -> Callable[[Callable[..., _T]], Callable[..., _T]]:def wrap(func: Callable[..., _T]) -> Callable[..., _T]:for value in values:if value in registry:raise ValueError(f'@value_dispatch: there is already a handler 'f'registered for {value!r}')registry[value] = funcreturn funcreturn wrapwrapper.register = registerwrapper.register_for_all = register_for_allreturn wrapper

使用如下: 

from value_dispatch import value_dispatch@value_dispatch
def get_user_type(type):"""处理不存在的情况"""return f'等级 {type} 不存在'# 普通用户
@get_user_type.register("normal_user")
def normal_user(type):"""大量的逻辑代码"""return type# 黄金用户
@get_user_type.register("gold_user")
def gold_user(type):"""大量的逻辑代码"""return type# 铂金用户
@get_user_type.register("platinum_user")
def platinum_user(type):"""大量的逻辑代码"""return type# 钻石用户
@get_user_type.register("diamond_user")
def diamond_user(type):"""大量的逻辑代码"""return type# 星耀用户
@get_user_type.register("starlight_user")
def starlight_user(type):"""大量的逻辑代码"""return type# 至尊用户
@get_user_type.register("superior_user")
def superior_user(type):"""大量的逻辑代码"""return typeif __name__ == '__main__':print(get_user_type("diamond_user"))

至此,是不是觉得自己的编码逻辑又进了一步,拜拜!

这篇关于Python开发中如何优雅的处理多重if...elif...判断的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/174291

相关文章

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

Python 安装和配置flask, flask_cors的图文教程

《Python安装和配置flask,flask_cors的图文教程》:本文主要介绍Python安装和配置flask,flask_cors的图文教程,本文通过图文并茂的形式给大家介绍的非常详细,... 目录一.python安装:二,配置环境变量,三:检查Python安装和环境变量,四:安装flask和flas

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

使用Python自建轻量级的HTTP调试工具

《使用Python自建轻量级的HTTP调试工具》这篇文章主要为大家详细介绍了如何使用Python自建一个轻量级的HTTP调试工具,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下... 目录一、为什么需要自建工具二、核心功能设计三、技术选型四、分步实现五、进阶优化技巧六、使用示例七、性能对比八、扩展方向建

基于Python打造一个可视化FTP服务器

《基于Python打造一个可视化FTP服务器》在日常办公和团队协作中,文件共享是一个不可或缺的需求,所以本文将使用Python+Tkinter+pyftpdlib开发一款可视化FTP服务器,有需要的小... 目录1. 概述2. 功能介绍3. 如何使用4. 代码解析5. 运行效果6.相关源码7. 总结与展望1

使用Python实现一键隐藏屏幕并锁定输入

《使用Python实现一键隐藏屏幕并锁定输入》本文主要介绍了使用Python编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入,这样就再也不用担心自己... 目录1. 概述2. 功能亮点3.代码实现4.使用方法5. 展示效果6. 代码优化与拓展7. 总结1.

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Python基础文件操作方法超详细讲解(详解版)

《Python基础文件操作方法超详细讲解(详解版)》文件就是操作系统为用户或应用程序提供的一个读写硬盘的虚拟单位,文件的核心操作就是读和写,:本文主要介绍Python基础文件操作方法超详细讲解的相... 目录一、文件操作1. 文件打开与关闭1.1 打开文件1.2 关闭文件2. 访问模式及说明二、文件读写1.

Python将博客内容html导出为Markdown格式

《Python将博客内容html导出为Markdown格式》Python将博客内容html导出为Markdown格式,通过博客url地址抓取文章,分析并提取出文章标题和内容,将内容构建成html,再转... 目录一、为什么要搞?二、准备如何搞?三、说搞咱就搞!抓取文章提取内容构建html转存markdown

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,