如何让 __radd__ 使用 numpy 数组

发布于 2024-11-09 09:43:58 字数 658 浏览 0 评论 0原文

考虑以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅冕 2024-11-16 09:43:58

当您执行 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 if a.__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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文