清理python切片?
我正在使用Python/ctypes包装一个C库。我正在包装的结构之一类似于数字向量,我希望相应Python类的getitem()方法支持切片。在C级,我有如下的片感知函数:清理python切片?,python,ctypes,Python,Ctypes,我正在使用Python/ctypes包装一个C库。我正在包装的结构之一类似于数字向量,我希望相应Python类的getitem()方法支持切片。在C级,我有如下的片感知函数: void * slice_copy( void * ptr , int index1 , int index2 , int step) { ... } def __getitem__(self , index): if isinstance( index , types.SliceType):
void * slice_copy( void * ptr , int index1 , int index2 , int step) {
...
}
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)
我的Pythongetitem()如下所示:
void * slice_copy( void * ptr , int index1 , int index2 , int step) {
...
}
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:]的情况下,开始属性将为-100,结束和步骤属性都将为无,即,在我将整数值传递给C函数slice_copy()之前,需要对它们进行清理。现在,这种清理并不困难,但我认为必要的功能已经包含在Python源代码中,或者说界面中确实有一个函数
slice
对象有一个Indexs()
方法,该方法接受序列的长度作为参数,并以元组的形式返回标准化的开始、停止和步长值。非常感谢您的调查-Joakim。为了简洁起见,我通常使用isinstance(index,int)
和isinstance(index,slice)
。