我正在使用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