带有__add__的自定义类与NumPy数组一起添加

问题描述 投票:5回答:1

我有一个自定义类,将__add__和__radd__实现为>

import numpy

class Foo(object):

    def __init__(self, val):
        self.val = val

    def __add__(self, other):
        print('__add__')
        print('type self = %s' % type(self))
        print('type other = %s' % type(other))
        return self.val + other

    def __radd__(self, other):
        print('__radd__')
        print('type self = %s' % type(self))
        print('type other = %s' % type(other))
        return other + self.val

我先测试__add __

r1 = Foo(numpy.arange(3)) + numpy.arange(3,6)
print('type results = %s' % type(r1))
print('result = {}'.format(r1))

并导致预期结果

>>> __add__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'numpy.ndarray'>
>>> type results = <type 'numpy.ndarray'>
>>> result = [3  5  7]

但是,测试__radd __

r2 = numpy.arange(3) + Foo(numpy.arange(3,6))
print('type results = %s' % type(r2))
print('result = {}'.format(r2))

我知道

>>> __radd__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'int'>
>>> __radd__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'int'>
>>> __radd__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'int'>
>>> type results = <type 'numpy.ndarray'>
>>> result = [array([3, 4, 5]) array([4, 5, 6]) array([5, 6, 7])]

这对我来说没有任何意义。 NumPy是否为任意对象重载__add__,然后优先于我的__radd__?如果是,他们为什么要这样做?此外,如何避免这种情况,我确实希望能够在左侧添加带有NumPy数组的自定义类。谢谢。

我有一个自定义类,将__add__和__radd__实现为导入numpy类Foo(object):def __init __(self,val):self.val = val def __add __(self,other):print('__ add __')...

python numpy operator-overloading
1个回答
0
投票

这被评论隐藏了,但应该是答案。

© www.soinside.com 2019 - 2024. All rights reserved.