我正在使用
Python / ctypes来包装C库.我包装的其中一个结构类似于数字向量,我希望相应Python类的getitem()方法支持切片.在C级,我有像这样的切片感知功能:
void * slice_copy( void * ptr , int index1 , int index2 , int step) {
...
}
我的Python getitem()看起来像这样:
def __getitem__(self , index):
if isinstance( index , types.SliceType):
# Call slice_copy function ...
# Need values for arguments index1, index2 and step.
elif isinstance( index , types.IntType):
# Normal index lookup
else:
Raise TypeError("Index:%s has wrong type" % index)
如果切片文字看起来像[1:100:10],则切片对象的开始,结束和步骤属性都被设置,但是例如在[-100:]的情况下,start属性为-100,end和step属性都是None,即在将整数值传递给C函数slice_copy()之前需要对它们进行清理.现在,这种清理并不是很困难,但我认为必要的功能已经包含在Python源代码中 – 或者?
最佳答案 界面中确实有一个功能. slice对象有一个indices()方法,它接受序列的长度作为参数,并将标准化的start,stop和step值作为元组返回.