【发布时间】:2011-09-08 22:03:56
【问题描述】:
我正在使用 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)。