如何让 __radd__ 使用 numpy 数组
考虑以下 python 代码:
class MyClass:
def __radd__(self, a):
print "foo", a
return a
p = MyClass()
要调用 radd,可以运行以下命令:
>>> print "bar"+p
foo bar
bar
这是预期的行为。 __add__
运行并失败,因此 __radd__
接管并处理这种情况。 但对于 numpy 数组,它的行为有点不同:
>>> v = np.arange(2)
>>> print v+p
foo 0.
foo 1.
[0. 1.]
似乎与上面的示例不同v.__add__
迭代地遍历 v
的组件并执行 p.__radd__< /代码> 他们。换句话说,它决定返回类型将是 ndarray (只要代码不崩溃)。我知道这是试图变得聪明的 numpy,但有时我希望我的班级能够处理算术方法。
是否可以使用 numpy 数组获得标准的 __radd__ 行为?
Consider the following python code:
class MyClass:
def __radd__(self, a):
print "foo", a
return a
p = MyClass()
To evoke radd the following can be run:
>>> print "bar"+p
foo bar
bar
This is the expected behavior. __add__
is run and fails, therefore __radd__
takes over and handles the situation.
But with numpy arrays it behaves a little differently:
>>> v = np.arange(2)
>>> print v+p
foo 0.
foo 1.
[0. 1.]
It seems that unlike the example abovev.__add__
itterativly goes through v
's components and performes p.__radd__
on them. In other words it has decided that the returning type will be an ndarray
(as long as the code don't crash). I get that this is numpy that tries to be smart, but somtimes I would like my class to handle the aritmethics.
Is it possible to get standard __radd__
behavior with numpy arrays?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您执行
a+b
时,a 通常首先会定义其含义:仅当a.__add__
时才会使用b.__radd__
没有实施。因此,在一般情况下,如果您想控制加法,则必须确保将对象放在第一位:b+a
。不过,根据文档,有一个例外。如果您子类化 numpy.ndarray 并定义一个 __radd__ 方法,那么首先会尝试该方法。因此,如果您的对象基于数组有意义,您就可以这样做。
When you do
a+b
, a normally gets first crack at defining what that means:b.__radd__
will only be used ifa.__add__
isn't implemented. So, in the general case, if you want to control addition, you have to make sure you put your object first:b+a
.According to the docs, though, there's an exception to that. If you subclass
numpy.ndarray
, and define an__radd__
method, that gets tried first. So, if it makes sense for your object to be based on an array, you can do that.