Aid NumPy从对象创建数组

时间:2018-01-10 17:37:22

标签: python numpy

如果一个对象既可迭代又可以有效地将自身转换为NumPy数组,那么我可以使用什么来帮助NumPy从中创建一个数组呢? __array_interface__

# Naive class that need to be iterated over
class myclass1():
    def to_array(self):
        return np.arange(4)

    def __getitem__(self, i):
        if i > 3:
            raise IndexError
        return i

    def __len__(self):
        return 4

# "Smart" class that knows how to construct NumPy buffer
class myclass2():
    # The result is always the same, but there is no buffer that is
    # part of the instance. Instead the buffer is generated when
    # calling to_array()
    def to_array(self):
        return np.arange(4)

    @property
    def __array_interface__(self):
        data = self.to_array()
        return {
            'shape': (4,),
            'data': data,
            'typestr': data.dtype.str,
        }


a = myclass1()
np.array(a)

b = myclass2()
np.array(b)

或者这是否会产生内存泄漏,双重释放或其他内存所有权问题?

0 个答案:

没有答案