python - 使类可转换为 ndarray

标签 python arrays class numpy subclass

除了通过子类化(例如,从list),我如何使Python对象隐式转换为ndarray

示例:

import numpy
arg=[0,1,2]
numpy.dot(arg,arg) # OK, arg is converted to ndarray

#Looks somewhat array like, albeit without support for slices
class A(object):
    def __init__(self, x=0,y=1,z=2):
        (self.x,self.y,self.z)=(x,y,z)
    def __getitem__(self, idx):
        if idx==0:
            return self.x
        elif idx==1:
            return self.y
        elif idx==2:
            return self.z
        else:
            raise IndexError()
    def __setitem__(self, idx, val):
        if idx==0:
            self.x=val
        elif idx==1:
            self.y=val
        elif idx==2:
            self.z=val
        else:
            raise IndexError()
    def __iter__(self):
        for v in (self.x,self.y,self.z):
            yield v
     # Is there a set of functions I can add here to allow
     # numpy to convert instances of A into ndarrays?
arg=A()
numpy.dot(arg,arg) # does not work

错误:

>>> scipy.dot(a,a) # I use scipy by default
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/dave/tmp/<ipython-input-9-f73d996ba2b6> in <module>()
----> 1 scipy.dot(a,a)

TypeError: unsupported operand type(s) for *: 'A' and 'A'

它正在调用 array(arg) 但会产生一个类似于 [arg,] 的数组,它是 shape==() 所以 dot 尝试将 A 实例相乘。

转换为 ndarray 需要复制数据,这是正常的(事实上,这是预料之中的)。

最佳答案

__len__ 似乎是关键功能:只需添加

def __len__(self):
    return 3

使该类在 numpy.dot 中工作。

关于python - 使类可转换为 ndarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30037104/

相关文章:

c# - 要使用只读属性还是方法?

c++ - 仅重新初始化派生类中的所有成员变量

python - 在 Tkinter 中为一组小部件添加滚动条

python - 运行主循环时读取 tmx 文件(用于 pygame)

python - Flask-SQLAlchemy:如何在执行连接操作后返回单个对象的列表?

c++ - 第一个字符串元素的地址产生意外结果

java - 使用反射通过网络加载类文件

python - DRF TypeError __init__() 恰好接受 1 个参数(给定 2 个)

php - 从 PHP 数组中提取行或列

javascript - 'this' 关键字在 map() 和 call() 中如何工作?