制作类可转换到ndarray(Make class convertable to ndarray)

2019-10-22 23:41发布

除了由子类(从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将需要复制数据。

Answer 1:

__len__似乎是关键特征:刚刚加入

def __len__(self):
    return 3

提出在班级工作numpy.dot



文章来源: Make class convertable to ndarray