【发布时间】:2018-08-13 08:22:06
【问题描述】:
我在 C Python 扩展中创建了自己的类。我希望它表现得像一个 numpy 数组。
假设我的班级是一个 myarray。我可以使用切片表示法对其进行索引。这意味着我对mapping_methods 的mp_subscript 函数的实现看起来是正确的。我可以进一步索引它,它会返回我想要的正确类型的元素。
# Create a new myarray object of 10 elements
a = myarray( 10 )
# Get a slice of this myarray, as a numpy.ndarray object
# returns new one created with PyArray_NewFromDescr (no copy)
b = a[2:4]
# What is the class of an indexed item in the slice?
print( b[0].__class__ )
<class 'numpy.int8'>
我还使用a[0] 在我自己的类型中实现了直接索引。为此,我尝试调用PyArray_GETITEM。但我得到的对象是int。
# Create a new myarray object of 10 elements
a = myarray( 10 )
# What is the class of an indexed item in the slice?
# returns the result of calling PyArray_GETITEM.
print( a[0].__class__ )
<class 'int'>
如何在我的 C 扩展中创建 numpy.int8 类型的对象?
【问题讨论】:
标签: python numpy cpython python-c-api