我有一个自定义类实现 __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
Run Code Online (Sandbox Code Playgroud)
我首先测试 __add__
r1 = Foo(numpy.arange(3)) + numpy.arange(3,6)
print('type results = %s' % type(r1))
print('result = {}'.format(r1))
Run Code Online (Sandbox Code Playgroud)
它导致了预期的结果
>>> __add__
>>> type self = <class '__main__.Foo'> …Run Code Online (Sandbox Code Playgroud)