【问题标题】:Using dict as switch statement in python在python中使用dict作为switch语句
【发布时间】:2026-01-16 14:55:02
【问题描述】:

我正在尝试使用字典作为 switch 语句从用户输入中调用各种方法。然而,似乎正在发生的事情是,无论用户选择什么方法,然后按照它们在我的字典中的列出顺序循环遍历所有方法,而不是在特定方法调用后退出。

我是 Python 新手,使用过 JAVA,它有一个 switch 语句,并且能够在 switch 中使用 break 关键字,而 python 没有。

我一直在研究 * 和 google,但对我的特定问题没有任何运气,因此我们将不胜感激。

完整代码如下:

import pymysql

# Open DB
db = pymysql.connect()

# Prepare a cursor object using  cursor() method
cursor = db.cursor()

# Create a Student Table
cursor.execute("DROP TABLE IF EXISTS Student")
cursor.execute("CREATE TABLE Student(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")

# Method for inserting new student mySQL
def insert() :
    name = input('Enter the Students name: ')
    instatmt = "INSERT INTO Student VALUES(NULL, '%s')" % (name)
    cursor.execute(instatmt)
    db.commit()

    return(print("Successfully inserted student"))

# Method for updating a student record mySQL
def update() :
    name = input('Enter the Students name: ')
    update = input('Enter the Updated name: ')

    upstatmt = "UPDATE Student SET Name='%s' WHERE Name='%s'" % (update, name)
    cursor.execute(upstatmt)
    db.commit()

    return(print("Successfully updated object"))

# Method for deleting a student record mySQL
def delete() :
    name = input('Enter the Students name: ')

    delstatmt = "DELETE FROM Student WHERE Name ='%s'" % (name)
    cursor.execute(delstatmt)
    db.commit()

    return(print("Successfully deleted object"))

# Method for retrieving a student record mySQL
def retrieve() :
    name = input('Enter the Students name: ')

    retstatmt = "SELECT * FROM Student WHERE Name ='%s'" % (name)
    display = cursor.execute(retstatmt)
    print(display)

    return(print("Object Retrieved..."))

# Call method requested by user    
def performAction(argument):

    switcher = {
        'I': insert(),
        'U': update(),
        'D': delete(),
        'R': retrieve(),
        'E': exit
    }
    func = switcher.get(argument, lambda: "Invalid Entry")
    print (func)

# while True :
action = input('Which Operation would you like to perform ( I : Insert, U : Update, D: Delete, R: Retrieve, E: Exit): ')
performAction(action)

# disconnect from server
db.close()

【问题讨论】:

  • 您正在调用该函数,而不是引用该函数。用insert(无括号)代替insert()
  • 'I': insert()这将返回一个带有dict['I']=the result of insert()的字典,你需要改为I:insert,然后像swicther['I']()一样调用

标签: python mysql dictionary switch-statement


【解决方案1】:

您正在调用这些函数,而不是将它们插入到您的字典中。试试这个:

def performAction(argument):
    switcher = {
        'I': insert,
        'U': update,
        'D': delete,
        'R': retrieve,
        'E': exit
    }
    func = switcher.get(argument, lambda: "Invalid Entry")
    result = func()
    print (func, result)

【讨论】:

  • 或许result = func() if func != 'Invalid Entry' else None
  • 在此感谢您的帮助,我的疏忽调用了函数!
  • @Alexander - 也许吧。但我认为让dict.get() 返回一个默认的可调用对象会使代码更具可读性。
【解决方案2】:

您正在调用字典中的函数,因此它们都被连续执行,然后再也不会执行。要解决此问题,请删除括号:

def performAction(argument):

    switcher = {
        'I': insert,
        'U': update,
        'D': delete,
        'R': retrieve,
        'E': exit
    }
    func = switcher.get(argument, lambda: print("Invalid Entry"))
    func()

虽然可行,但这是一种非常规的做事方式 尝试做,并且可以写成更易读的方式:

def performAction(argument):
    if argument == 'I':
        insert()
    elif argument == 'U':
        update()
    elif argument == 'D':
        delete()
    elif argument == 'R':
        retrieve()
    elif argument == 'E':
        exit()
    else:
        print("Invalid Entry")

Python 不是 Java,所以没有必要假装它是。

【讨论】:

  • 我不认为它非常规。它只是一个历史悠久的跳台。
  • @tdelaney 这是一个 python dict 被用作 switch 语句。没有什么是正常的或 pythonic 的。
  • 使用elif,因为这些值是互斥的。
  • 您的else: 仅附加到最后一个if,因此当输入前4 个操作之一时,它将打印Invalid Entry
  • @tdelaney 在代码审查期间询问任何经验丰富的开发人员他们更喜欢哪一个。 99/100 的开发人员会说使用 if 语句,而不是非常规的字典方法。
【解决方案3】:

带参数运行程序

updatedb.py --action insert more

action = input('您要执行哪个操作(I:插入,U:更新,D:删除,R:检索,E:退出):')

替换为

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-action", dest="action", nargs=1, default="exit", choices=['insert', 'exit', 'delete'], type=str)
args = parser.parse_args()
>>> args
Namespace(action='insert')
>>> args.action
'insert'

执行动作(动作)

替换为

你可以使用eval()来调用函数

result = eval(args.action)

【讨论】: