不,不是全部!
正如前面已经提到的,首先要知道的是slice是一个类,不是返回对象的函数。
slice()实例的第二个用途是在创建自己的对象时将参数传递给getitem()和getslice()方法,这些对象的行为类似于字符串、列表和其他支持切片的对象。
当你这样做时:print "blahblah"[3:5]
自动转换为:print "blahblah".__getitem__(slice(3, 5, None))
因此,当您编写自己的索引和切片对象时:class example:
def __getitem__ (self, item):
if isinstance(item, slice):
print "You are slicing me!"
print "From", item.start, "to", item.stop, "with step", item.step
return self
if isinstance(item, tuple):
print "You are multi-slicing me!"
for x, y in enumerate(item):
print "Slice #", x
self[y]
return self
print "You are indexing me!\nIndex:", repr(item)
return self
试试看:>>> example()[9:20]
>>> example()[2:3,9:19:2]
>>> example()[50]
>>> example()["String index i.e. the key!"]
>>> # You may wish to create an object that can be sliced with strings:
>>> example()["start of slice":"end of slice"]
较旧的Python版本支持方法getslice(而不是getitem)。检查getitem是否有切片是一个很好的做法,如果有,请将其重定向到getslice方法。这样,您将具有完全的向后兼容性。
这就是numpy使用slice()对象进行矩阵操作的方式,很明显,它经常被间接地用于任何地方。
本文详细解释了Python中slice类的使用方式及其在自定义对象中的应用,通过实例展示了如何利用slice实现类似列表和字符串的切片功能,并讨论了新旧Python版本中getitem与getslice方法的区别。
1421

被折叠的 条评论
为什么被折叠?



