【问题标题】:Sanitize python slice?消毒python切片?
【发布时间】: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)

标签: python ctypes


【解决方案1】:

界面中确实有一个功能。 slice 对象有一个 indices() 方法,该方法接受序列的长度作为参数,并以元组的形式返回标准化的开始、停止和步长值。

【讨论】:

  • 非常感谢您的调查 - Joakim。
猜你喜欢
  • 2021-11-26
  • 2015-09-07
  • 2019-09-05
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 2012-07-05
  • 2023-04-04
  • 2017-06-24
相关资源
最近更新 更多