消毒Python切片?

4

我正在使用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],则切片对象的start、end和step属性都已设置,但例如在[-100:]的情况下,start属性将为-100,而end和step属性都将为None,即它们需要在将整数值传递给C函数slice_copy()之前进行清理。现在,这种清理并不是非常困难,但我认为必要的功能应已包含在Python源代码中了,难道没有吗?


通常我会使用isinstance(index, int)isinstance(index, slice)来简洁地表达。 - Sven Marnach
1个回答

2

界面中确实有一个函数。 slice 对象有一个 indices() 方法,它接受序列的长度作为参数,并返回标准化的起始、结束和步骤值作为元组。


1
非常感谢您的调查 - Joakim。 - user422005

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接