给出的这段代码是我程序的一部分。在这里,我想将3个函数减少为1个,因为除了1行外它们完全相似。我读了有关传递函数的信息(使该函数为Bar
),并将其参数作为另一个函数的参数(使该函数称为Foo
)。
但是在这种情况下,我无法更改功能Foo
。这里我的Foo
函数是.clicked.connect()
,而addXMin
是我的函数Bar
。我想将Bar
及其参数num
传递给Foo
,在这里我无法更改Foo
中发生的事情。有没有一种方法可以将3个函数简化为1,并将15
,10
和5
作为该单个函数的参数传递?
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)
答案 0 :(得分:1)
如果connect
接受单个参数,则可以这样使用匿名函数(Python中的lambda
):
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)
答案 1 :(得分:1)
您可以创建一个通用函数,然后使用functools.partial
将变量绑定到参数:
def addMin(self, mins_to_add):
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)
add5Min, add10Min, add15Min = [functools.partial(self.addMin, x) for x in range(5, 20, 5)]
或直接连接:
self.add15m.clicked.connect(partial(self.addMin, 5))