Pass argument and function as argument in python
本问题已经有最佳答案,请猛点这里访问。
给出的代码是我程序的一部分。这里,我想将3个函数减少到1,因为它们除了1行之外完全相似。我读过关于传递函数(让这个函数为
但是在这个场景中,我不能更改函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | self.add15m.clicked.connect(self.add15Min) self.add10m.clicked.connect(self.add10Min) self.add5m.clicked.connect(self.add5Min) def add15Min(self): global mins, secs, time time = self.lineEdit.text() mins = int((time.split(':'))[0]) mins+=15 #The only different line secs = int((time.split(':'))[1]) time = str(mins).zfill(2) +":" + str(secs).zfill(2) self.lineEdit.setText(time) def add10Min(self): global mins, secs, time time = self.lineEdit.text() mins = int((time.split(':'))[0]) mins+=10 #The only different line secs = int((time.split(':'))[1]) time = str(mins).zfill(2) +":" + str(secs).zfill(2) self.lineEdit.setText(time) def add5Min(self): global mins, secs, time time = self.lineEdit.text() mins = int((time.split(':'))[0]) secs = int((time.split(':'))[1]) mins+=5 #The only different line time = str(mins).zfill(2) +":" + str(secs).zfill(2) self.lineEdit.setText(time) |
您可以创建一个通用函数,然后使用EDOCX1&2
ZZU1
Or connect directly:
1 | self.add15m.clicked.connect(partial(self.addMin, 5)) |
如果接受单一论据,你可以使用一个匿名函数
1 2 3 4 5 6 7 8 9 | self.add5m.clicked.connect(lambda: self.addMin(5)) def addMin(self, minutes): time = self.lineEdit.text() mins = int((time.split(':'))[0]) secs = int((time.split(':'))[1]) mins += minutes time = str(mins).zfill(2) +":" + str(secs).zfill(2) self.lineEdit.setText(time) |