所以我得到了一個基本的解決方案:將值包裝在一個對象中(MagicNumber
),它重載了算術運算符。
RunningTotal = {}
class MagicNumber(object):
def __init__(self, name, value):
self.name = str(name)
if isinstance(value, MagicNumber):
value = value.value
self.value = float(value)
def __str__(self):
return str(self.value)
def __add__(self, other):
if not isinstance(other, MagicNumber):
other = MagicNumber('literal', float(other))
result = MagicNumber(self.name, self.value + other.value)
RunningTotal[other.name] = result.value
return result
def __radd__(self, other):
if not isinstance(other, MagicNumber):
other = MagicNumber('literal', float(other))
result = MagicNumber(self.name, other.value + self.value)
RunningTotal[self.name] = result.value
return result
所以當你使用這樣的:
A = MagicNumber('A', 1)
B = MagicNumber('B', 2)
C = MagicNumber('C', 3)
result = A + B + C
您在RunningTotal字典中獲取這些值:
B: 3
C: 6
您也可以重載其他運營商(子,MUL,DIV等等,包括他們的反面同行)。有關可能的過載,請參閱python docs。