Evp*_*pok 5 python typechecking slice magic-methods
我有一个自定义序列类型。它本质上是列表加布尔标志的包装,我希望它模仿通常的不可变序列行为。
我的问题是切片。我知道在Python 3中,实现它的__getitem__(key)方法是有一个方法,如果%key一个索引是一个项目,则返回一个项目;如果%key是一个切片对象,则返回一个切片的序列。但是我应该如何区分这些情况?
我基本上有两个假设。
sliced_list = self.wrapped_list[key]
if isinstance(key, slice):
return MyCustomSequenceType(sliced_list, boolean_flag)
return sliced_list
Run Code Online (Sandbox Code Playgroud)
但这是邪恶的,不是吗?要么
sliced_list = self.wrapped_list[key]
try:
return MyCustomSequenceType(sliced_list, boolean_flag)
except TypeError:
return sliced_list
Run Code Online (Sandbox Code Playgroud)
后者看起来更pythonic。它依赖于MyCustomSequenceType.__init__(self, datas, flag)调用len(datas)的事实,因此TypeError如果%datasis是,则会引发integer。但是,如果再__init__提出TypeError另一个随机问题,那将是无法追踪的。另外,http: //wiki.cython.org/enhancements/numpy/getitem暗示了isinstance速度更快(实际上更容易被优化)。
那我该怎么办?
您可以浏览标准库并复制在那里完成的工作。例如,calendar.py具有:
def __getitem__(self, i):
funcs = self._months[i]
if isinstance(i, slice):
return [f(self.format) for f in funcs]
else:
return funcs(self.format)
Run Code Online (Sandbox Code Playgroud)
它显示了通过简单地将索引或切片传递到基础列表来进行显式检查isinstance 和部分回避问题的方法。