在下面的示例中,我将需要执行此功能约7次。例如,唯一的变化将是strength
,而不是perception
。在您看到strength
一词的任何地方,都需要对其进行更改,包括在Qt函数中,例如self.strengthSpin.setValue()
。
有没有一种方法可以完成多次复制/粘贴代码?
if stat == "strength":
newValue = self.strengthSpin.value()
varChange = newValue - strength
if varChange > 0:
if statPoints - varChange >= 0:
statPoints -= varChange
self.statPointsLCD.setProperty("intValue", statPoints)
strength += varChange
self.strengthSpin.setValue(strength)
else:
print("not enough stat points")
self.strengthSpin.setValue(strength)
else:
if newValue > 0:
print("should be adding")
statPoints -= varChange
self.statPointsLCD.setProperty("intValue", statPoints)
strength += varChange
self.strengthSpin.setValue(strength)
else:
print("must be at least 0")
self.strengthSpin.setValue(strength)
答案 0 :(得分:0)
是的,但是您必须将strength
和statPoints
保存为'self'的属性(或将它们传递给方法,然后再从中返回它们):
def update_value(self, name): # name is 'strength'
spin = getattr(self, name + 'Spin')
newValue = spin.value()
oldValue = getattr(self, name)
varChange = newValue - oldValue
if varChange > 0:
if self.statPoints - varChange >= 0:
self.statPoints -= varChange # if this variable should be different for different names, use setattr instead
self.statPointsLCD.setProperty("intValue", statPoints)
setattr(self, name, newValue)
spin.setValue(newValue)
else:
print("not enough stat points")
spin.setValue(oldValue)
else:
if newValue > 0:
print("should be adding")
self.statPoints -= varChange
self.statPointsLCD.setProperty("intValue", statPoints)
setattr(self, name, newValue)
spin.setValue(newValue)
else:
print("must be at least 0")
spin.setValue(oldValue)