TypeError:不支持+的操作数类型:“int”和“IntervalMap”

2024-10-01 15:39:21 发布

您现在位置:Python中文网/ 问答频道 /正文

已获得向现有项目添加功能的目标-IntervalMap project!。 由于内部运算符(__add____mul__等)尚未实现,因此需要订阅它们。在

这是我在__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

输出

^{pr2}$

想成为abble给intervalmap对象添加一个常量吗 位置,右或左操作数。如何将数字作为左操作数相加?在

顺便问一下,有没有人看到了一种通用的方法来实现这一点? 就像传递给更新函数x.update(y, lambda x,y: x+y)来执行相同的操作。在


Tags: inselfnoneaddforifslicepoint
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:21

除了__add__,您还可以定义__radd__方法。在

套用documentation

__radd__ is only called if the left operand does not support the add operation 
and the operands are of different types. [2] 
For instance, to evaluate the expression x + y, where y is an instance of a class 
that has __radd__() method, 
y.__radd__(x) is called if x.__add__(y) returns NotImplemented.

应该是这样的:

^{pr2}$

相关问题 更多 >

    热门问题