0
實現了將功能添加到現有項目的目標 - IntervalMap project!。 由於內部運營商(__add__
,__mul__
等)尚未實施,因此需要訂閱他們。TypeError:不支持的操作數類型爲+:'int'和'IntervalMap'
這是我在__add__
內置實現來執行 intervalmap另外的代碼。
# ...
def __add__(self, other):
"""
a = x + y
"""
aux = intervalmap()
if isinstance(other, self.__class__):
ruler = self._bounds + other._bounds
ruler = map(ruler.sort(), ruler)
for i, x in enumerate(ruler):
if i > 0:
_slice = slice(ruler[i-1], x, None)
point = (_slice.start + _slice.stop)/2.0
if self[point] is None:
aux.__setitem__(_slice, other[point])
elif other[point] is None:
aux.__setitem__(_slice, self[point])
else:
aux.__setitem__(_slice, self[point] + other[point])
if isinstance(other, (int,float)):
for i, x in enumerate(self._bounds):
if i > 0:
point = (self._bounds[i-1] + x)/2
aux[self._bounds[i-1]:x] = self[point] + other
return aux
# ...
if __name__ == '__main__':
x = intervalmap()
y = intervalmap()
x[1:2] = 6
x[4:5] = 1
x[7:8] = 5
y[0:3] = 4
y[3:6] = 2
y[6:9] = 11
print x
print y
輸出
>>> {[1, 2] => 6, [4, 5] => 1, [7, 8] => 5}
>>> {[0, 3] => 4, [3, 6] => 2, [6, 9] => 11}
a = x + y
b = y + x
print a
print b
>>> {[0, 1] => 4, [1, 2] => 10, [2, 3] => 4, [3, 4] => 2, [4, 5] => 3, [5, 6] => 2, [6, 7] => 11, [7, 8] => 16, [8, 9] => 11}
>>> {[0, 1] => 4, [1, 2] => 10, [2, 3] => 4, [3, 4] => 2, [4, 5] => 3, [5, 6] => 2, [6, 7] => 11, [7, 8] => 16, [8, 9] => 11}
a = y + 2
print a
b = 2 + y
print b
>>> {[0, 3] => 6, [3, 6] => 4, [6, 9] => 13}
Traceback (most recent call last): File "/home/pc/workspace/simulador-mti/source/y.py", line 73, in <module> b = 2 + y
TypeError: unsupported operand type(s) for +: 'int' and 'IntervalMap'
想成爲abble到恆定數量添加到intervalmap對象不管 的位置,右或左操作數。我如何添加一個數字作爲左操作數?
順便說一句,有沒有人看到一種通用的方式來做到這一點? 就像傳遞給更新函數x.update(y, lambda x,y: x+y)
來執行相同的事情。
問題解決了。謝謝。 – Jack