【问题标题】:Python getslice Item Operator Override Function not workingPython getslice 项目运算符覆盖功能不起作用
【发布时间】: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


【解决方案1】:

如 cmets 中所述,__getitem__ 方法采用 slice 类型的一个参数,您可以通过 slice.startslice.stop 访问范围的开始/结束,这是一个带有更多调试输出的示例显示正在发生的事情:

class FakeList:

    def __getitem__(self, slice_):
         print('slice_', slice_)
         print('type(slice_)', type(slice_))
         print('dir(slice_)', dir(slice_))
         return str(slice_.start) + " to " + str(slice_.stop)

f = FakeList()

print(f[1:4])

输出:

slice_ slice(1, 4, None)

type(slice_) <class 'slice'>

dir(slice_) ['__class__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__',
'__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'indices', 'start', 'step', 'stop']

1 to 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-23
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    相关资源
    最近更新 更多