本文介绍了使类可转换为ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
除了通过子类化(例如,从list
继承)之外,如何使python对象隐式转换为ndarray
?
Other than by subclassing (from list
for example) how do I make a python object implicitly convertable to 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
实例相乘在一起.
It's calling array(arg)
but that yields an array like [arg,]
, it's shape==()
so dot
tries to multiply the A
instances together.
可以(实际上是预期的)转换为ndarray
时需要复制数据.
It's ok (in fact, expected) that the conversion to ndarray
will require copying the data.
推荐答案
__len__
似乎是关键功能:只需添加
__len__
seems to be the key feature: just adding a
def __len__(self):
return 3
使类在numpy.dot
中工作.
这篇关于使类可转换为ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!