- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在包含 numpy 数组作为属性的类中重载运算符时,我遇到了一个问题。根据操作数的顺序,结果类型将是我的 A 类(期望的行为)或 numpy 数组。如何让它始终返回 A 的实例?
例子:
import numpy as np
class A(object):
""" class overloading a numpy array for addition
"""
def __init__(self, values):
self.values = values
def __add__(self, x):
""" addition
"""
x = np.array(x) # make sure input is numpy compatible
return A(self.values + x)
def __radd__(self, x):
""" reversed-order (LHS <-> RHS) addition
"""
x = np.array(x) # make sure input is numpy compatible
return A(x + self.values)
def __array__(self):
""" so that numpy's array() returns values
"""
return self.values
def __repr__(self):
return "A object: "+repr(self.values)
A 的实例:
>>> a = A(np.arange(5))
这按预期工作:
>>> a + np.ones(5)
A object: array([ 1., 2., 3., 4., 5.])
这不是:
>>> np.ones(5) + a
array([ 1., 2., 3., 4., 5.])
即使这很好:
>>> list(np.ones(5)) + a
A object: array([ 1., 2., 3., 4., 5.])
在第二个示例中发生的是根本没有调用 radd,而是调用了 np.ones(5) 中的 numpy 方法 __add__
。
我尝试了来自 this post 的一些建议但 __array_priority__
似乎没有任何区别(在 seberg 评论后编辑:至少在 numpy 1.7.1 中,但可以在较新的版本上工作),并且 __set_numeric_ops__
导致分段故障...我想我做错了什么。
有什么建议适用于上面的简单示例(同时保留 __array__
属性)?
编辑:我不希望 A 成为 np.ndarray 的子类,因为这会带来我想避免的其他并发症 - 至少现在是这样。请注意,pandas 似乎已经解决了这个问题:
import pandas as pd
df = pd.DataFrame(np.arange(5))
type(df.values + df) is pd.DataFrame # returns True
isinstance(df, np.ndarray) # returns False
我很想知道这是怎么做到的。
解决方案:除了子类化的 M4rtini 解决方案之外,还可以将 __array_wrap__
属性添加到类 A(以避免子类化)。更多 here .根据 seberg 的说法,__array_priority__
也可以在较新的 numpy 版本上工作(见评论)。
最佳答案
使A
成为np.ndarray
的子类,Python 将首先 调用您的A.__radd__
方法。
来自object.__radd__
documentation :
Note: If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations.
通过子类化您的 A
对象确实能够拦截添加:
>>> import numpy as np
>>> class A(np.ndarray):
... """ class overloading a numpy array for addition
... """
... def __init__(self, values):
... self.values = values
... def __add__(self, x):
... """ addition
... """
... x = np.array(x) # make sure input is numpy compatible
... return A(self.values + x)
... def __radd__(self, x):
... """ reversed-order (LHS <-> RHS) addition
... """
... x = np.array(x) # make sure input is numpy compatible
... return A(x + self.values)
... def __array__(self):
... """ so that numpy's array() returns values
... """
... return self.values
... def __repr__(self):
... return "A object: "+repr(self.values)
...
>>> a = A(np.arange(5))
>>> a + np.ones(5)
A object: array([ 1., 2., 3., 4., 5.])
>>> np.ones(5) + a
A object: array([ 1., 2., 3., 4., 5.])
研究 Subclassing ndarray
documenation注意事项和影响。
关于python - 如何使 __add__ 的 numpy 重载独立于操作数顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22632937/
int enter_path(char** path) { char* standard = "./questions.txt"; printf("\n\t%s\n\t%s",
我有以下几行代码: #define PORT 9987 和 char *ptr = (char *)&PORT; 这似乎适用于我的服务器代码。但是当我在我的客户端代码中写它时,它给出了这个错误信息:
大家好,我在成员函数中有以下内容 int tt = 6; vector>& temp = m_egressCandidatesByDestAndOtMode[tt]; set& egressCandi
我知道您可以通过以下方式在正则表达式中使用 NOT 操作数: [^AB] :匹配除 "A" 之外的任何内容或"B" A(?!B) :匹配"A" ,后面不跟 "B" (?
我的代码如下,下面还解释了为什么会发生左值; typedef struct test_item { char id[MENU_NAME_LEN + NULL_SPACE]; MenuF
我正在审查一些 javascript 代码,程序员在几个地方使用了 >>。我试图在谷歌上搜索但找不到这个操作数/运算符的作用。所以我来了。下面的代码示例: var triplet=(((binarra
我使用以下行(希望这是最佳实践,如果不正确请纠正我)来处理命令行选项: #!/usr/bin/bash read -r -d '' HELP &2 for i in "${invalid_opti
我正在尝试编辑一个计时器应用程序,出现了这行代码。我该如何解决? let styleMask: Int = NSClosableWindowMask | NSTitledWindowMask 错误是:
我可以得到两个特定日期之间的差异,这将等于日期总数。现在我想将工作日除以总天数并得到整数输出。 @IBAction func go(_ sender: UIButton) { let con
我的项目有一个问题,它应该使用一个线程将每一行相加,然后将它们全部相加,但是我收到一个错误,指出左值需要作为一元 '&"操作数 pthread_create(&tid, NULL, &sum_line
我的代码有问题。有以下功能: static Poly PolyFromCoeff(int coeff); static Mono MonoFromPoly(const Poly *p, int exp
在 C# 中是否没有字符串的 OR 操作数? 我正在查看 Microsoft C# 操作数页面 - 没有关于字符串的任何类型的 OR。 我有一个要写的 if 语句: if (Convert.ToStr
下面的函数左移一个double操作数: double shl(double x,unsigned long long n) { unsigned long long* p = (unsigne
我在 Linux 中使用了以下简单的 ksh 脚本 #!/bin/ksh set -x ### Process list of *.dat files if [ -f *.dat ] then pri
我有一个使用 Entity Framework 的查询。它有许多不同的操作数,我对其优先级感到困惑。我得到了错误的结果。我需要所有 IsPaid == true 或 IsPaid == null 的记
我有以下代码来尝试创建一个约束数组以添加到 View 中: let views = ["button": button] let metrics = ["margin": 16] var constr
这个问题在这里已经有了答案: How to compare one value against multiple values - Swift (8 个答案) 关闭 6 年前。 我有一种情况,我必须
我使用 jquery $.ajax 将请求发送到服务器,它返回 JSON。 $.ajax({ url: 'moreMonth.ajax', data: { startIndex: id },
我的问题是程序没有按照“他”的预期读取代码。 我有 if (hero.getPos() == (6 | 11 | 16)) { move = new Object[] {"Up", "Righ
我在对象中创建线程时遇到问题。错误是需要作为一元“&”操作数的左值 CPP文件 #include "AirQ.h" static int i=0; AirQ::AirQ(int pinNo, bool
我是一名优秀的程序员,十分优秀!