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

3

我有一个使用PyQt4在Python中的函数,当你点击一个按钮时会弹出一个消息框。我使用'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()

4
可能是Python中switch语句的替代方案?的重复问题。 - takendarkk
1个回答

6
您的字典应该是这样的:
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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接