【发布时间】:2016-04-19 19:00:01
【问题描述】:
练习here 发布的示例以学习 Python OOP。我正在寻找“1 到 4”的输出,但它却抛出了下面的错误。
class FakeList:
def __getslice___(self,start,end):
return str(start) + " to " + str(end)
f = FakeList()
f[1:4]
注意:使用f.__getitem__(1, 4) 会产生正确的输出——“1 到 4”,如上面的链接所示。
Traceback(最近的调用 最后)在() ----> 1 f[1:4]
TypeError: 'FakeList' 对象不可下标
【问题讨论】:
-
Python 版本是多少?
-
不要使用
__getslice__,它早已被弃用并在Python 3中被删除。使用__getitem__,它支持切片对象。 -
使用 'getitem' 代替仍然会导致错误。
-
使用“getitem”时,新错误显示为:“TypeError: __getitem__() missing 1 required positional argument: 'end'”
标签: python class oop operators