如何在Python中使用字典而不是if语句? [英] How to use dictionary instead of if statement in python?

查看:361
本文介绍了如何在Python中使用字典而不是if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function that pops-up a message box after you click on a button using PyQt4 in python. I use 'sender()' to determine which button was clicked and then set the text of pop-up window accordingly. This function works perfectly with 'if statements'. However I was wondering how do I write a function with same functionality using a dictionary (since there is no switch statement in python and there are too many if statements in my code)?

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",
}

然后,您可以像访问任何词典一样访问值

Then you can access the values like you would any dictionary

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中使用字典而不是if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆