如何在 python 中使用字典而不是 if 语句?

How to use dictionary instead of if statement in python?

我在python中有一个使用PyQt4点击按钮后弹出消息框的功能。我使用 'sender()' 来确定单击了哪个按钮,然后相应地设置弹出窗口的文本 window。此函数与 'if statements' 完美配合。但是我想知道如何使用字典编写具有相同功能的函数(因为 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()