【问题标题】:Overriding slicing on custom object (Python) [duplicate]覆盖自定义对象上的切片(Python)[重复]
【发布时间】:2016-07-24 04:18:47
【问题描述】:

我有一个简单的类,它将对象列表作为输入,我想确保我可以对该操作执行切片。

class MyClass(AbstractLocationClass):
    def __init__(locations=None, **kwargs):
       if locations is None:
           locations = []
       self._locations = locations
       #... do other stuff with kwargs..

我希望允许用户执行以下操作:

 m = MyClass(locations=[[1,2],[2,3],[3,4]])
 sliced = m[0:1]
 print sliced 
 >>> [[1,2],[2,3]]

我知道我必须重写 __getitem__,但我不确定如何处理所有符号类型,如 obj[0]、obj[1:2] 等...

有人可以就实现此功能的正确方法提出建议。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    我发现我需要检查索引是否为slice 类型

    #----------------------------------------------------------------------
    def __getitem__(self, index):
        """slicing"""
        if len(self) == 0:
            return []
    
        if isinstance(index, slice):
            return self._locations[index]
        else:
            if index <= len(self) -1:
                return self._locatios[index]
            else:
                raise ValueError("Invalid index")
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 2019-11-16
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2020-07-07
      • 2015-10-18
      相关资源
      最近更新 更多