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

sey*_*yet 3 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()
Run Code Online (Sandbox Code Playgroud)

Pat*_*ugh 6

你的字典看起来像

button_dict = {
    self.button1: "Message 1",
    self.button2: "Message 2",
    self.button36: "Message 36",
}
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)