【发布时间】:2021-05-28 09:43:37
【问题描述】:
我正在尝试找到一种有效且安全的方法来根据用户输入的交易名称调用不同的函数。有 100 多种不同的交易。 100“IF”可以完成这项工作,但是,我想找到一种更有效的方式来调用事务。 “eval”会这样做,但我读到不应该使用它,因为用户可以输入任何事务名称。
from operator import methodcaller
import sys
from PyQt5.QtWidgets import (QMainWindow,QToolBar,QLineEdit,
QLabel, QApplication)
def one():
print ("1")
def two():
print ("2")
def three():
print("3")
class main_menu(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
menuBar = self.menuBar()
self.ToolBar = QToolBar()
self.ToolBar.setMovable(False)
self.addToolBar(self.ToolBar)
self.tcode = QLineEdit(maxLength=5)
self.tcode.returnPressed.connect(self.tcode_action)
self.ToolBar.addWidget(QLabel(" Transaction : "))
self.ToolBar.addWidget(self.tcode)
def tcode_action(self):
## if self.tcode.text() == "one":
## one()
## if self.tcode.text() == "two":
## two()
## if self.tcode.text() == "three":
## three()
## eval(self.tcode.text()+"()")
def main(args):
app = QApplication(sys.argv)
mm = main_menu()
mm.show()
sys.exit(app.exec_())
if __name__=="__main__":
main(sys.argv)
【问题讨论】:
-
附注,因为 Anurag Regmi 已经回答了这个问题:始终使用
if --> elif --> else和大量 if 。如果你不这样做,即使在 if 已经匹配之后,它也会执行其余的 ifs...
标签: python eval qmainwindow