python - 如何在Python中使用字典代替if语句?

标签 python dictionary if-statement switch-statement pyqt4

我有一个函数,在 python 中使用 PyQt4 单击按钮后会弹出一个消息框。我使用“sender()”来确定单击了哪个按钮,然后相应地设置弹出窗口的文本。该函数与“if 语句”完美配合。但是我想知道如何使用字典编写具有相同功能的函数(因为Python中没有switch语句,并且我的代码中有太多if语句)?

def pop_up(self):
    msg = QtGui.QMessageBox()
    msg.setIcon(QtGui.QMessageBox.Information)
    sender = self.MainWindow.sender()

    if sender is self.button1:
        msg.setText("show message 1")
    elif sender is self.button2:
        msg.setText("show message 2")
    elif sender is self.button3:
        msg.setText("show message 3")
    elif sender is self.button4:
        msg.setText("show message 4")
    elif sender is self.button5:
        msg.setText("show message 5")
    elif sender is self.button6:
        msg.setText("show message 6")
    .
    .
    .
    .
    .
    elif sender is self.button36:
        msg.setText("show message 36")


    msg.exec()

最佳答案

你的字典看起来像这样

button_dict = {
    self.button1: "Message 1",
    self.button2: "Message 2",
    self.button36: "Message 36",
}

然后您可以像访问任何字典一样访问这些值

def pop_up(self):
    msg = QtGui.QMessageBox()
    msg.setIcon(QtGui.QMessageBox.Information)
    sender = self.MainWindow.sender()
    message_text = button_dict[sender]
    msg.setText(message_text)
    msg.exec()

关于python - 如何在Python中使用字典代替if语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49881114/

相关文章:

javascript - 如何知道删除函数后数组/对象是否为空?

java - else if 语句内的 for 循环

JAVA初学者: IF statement not working as intended - body of code not being called when it should?

python - 如何提高Python代码速度

python - NumPy 一维数组切片

python - 我怎样才能在 PyQt4 中有一个动画系统托盘图标?

python - 元组在赋值中解包

python - Pandas:选择字典包含特定键的行

c++ - 在 std::map 上使用 Lambda 函数

python - 计算行日期之前 x 天的出现次数