前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python:减少 if-else 结构

Python:减少 if-else 结构

作者头像
雷子
发布2023-11-29 14:12:20
1780
发布2023-11-29 14:12:20
举报

经常在代码中,会遇到,有大量的写if ...else...结构的内容,但是如果大量的if else,可能会减少代码的可阅读性,那么我们是否可以有方案减少if...else...呢,答案是可以的。

一、字典方式

代码语言:javascript
复制
def fun1():
    return "fun1"

def fun2():
    return "fun 2"

def fun3():
    return "fun 3"

options = {
    '1': fun1,
    '2': fun2,
    '3': fun3
}

choice = input("Enter choice (1, 2, 3): ")

if choice in options:
    result = options[choice]()
    print(result)
else:
    print("Invalid choice")

结果:

代码语言:javascript
复制
Enter choice (1, 2, 3): 1
fun1

是不是用了很少的if ...else...

二、使用策略模式

代码语言:javascript
复制
class fun1:
    def execute(self):
        return "fun 1"

class fun2:
    def execute(self):
        return "fun 2"

class fun3:
    def execute(self):
        return "fun 3"

class Context:
    def __init__(self, strategy):
        self.strategy = strategy

    def execute_action(self):
        return self.strategy.execute()

options = {
    '1': fun1,
    '2': fun2,
    '3': fun3
}
def run(choice):
    if choice in options.keys():
        context = Context(options[choice]())
    else:
        print("Invalid choice")
    print(context.execute_action())
if __name__=="__main__":
    run("1")

执行结果:

这样很简单的就实现了,而且想要增加新的方案也很简单,不用增加if ...else...结果就可以实现了。

三、使用多态

代码语言:javascript
复制
class BaseAction:
    def execute(self):
        pass

class Fun1(BaseAction):
    def execute(self):
        return "Fun1"

class Fun2(BaseAction):
    def execute(self):
        return "Fun2"

class Fun3(BaseAction):
    def execute(self):
        return "Fun3"

# 统一调用执行方法
def exec_fun(fun):
    return fun.execute()

options = {
    '1': Fun1,
    '2': Fun2,
    '3': Fun3
}
def run(chos):
    if chos in options.keys():
        print(exec_fun(options[chos]()))
if __name__=="__main__":
    run("1")

看下结果:

四、使用装饰器

代码语言:javascript
复制
def choice_val(func):
    def inner(*args, **kwargs):
        choice = args[0]
        if choice in ('1', '2', '3'):
            return func(*args, **kwargs)
        else:
            return "Invalid choice"
    return inner

@choice_val
def run_action(choice):
    actions = {
        '1': "fun 1",
        '2': "fun 2",
        '3': "fun 3"
    }
    return actions[choice]

choice = "1"
result = run_action(choice)
print(result)

结果:

当然 还有其他方式可以实现减少if...else...,这里只是简单的举例。大家可以根据自己的实际的代码,进行选择适用自己的方式。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-11-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 雷子说测试开发 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档