What should I use instead of .__getslice__?

余生长醉 提交于 2019-12-11 03:15:53

问题


I'm in the process of porting a library to Python 3. I found this method:

def __getslice__(self, index, listget=list.__getslice__):
    self._resolve()
    return listget(self, index)

which raises an error since .__getslice__ is deprecated. I looked at the documentation and it seems like .__getitem__ is what most people are using to replace .__getslice__. The only issue is that this library has a method exactly like the above method except it's called __getitem__ and listget=list.__getitem__). I can't tell why they made this distinction in the code, but it seems like the original designers of the library wanted to preserve the unique functionality of both methods. Is there any way I can keep to this while porting over to Python 3?


回答1:


You should be able to simply delete the __getslice__ method all together. Now (in python3.x) __getitem__ handles the same cases that __getslice__ used to handle in addition to the cases that __getitem__ handled -- SO, in python3, the __getslice__ method on the custom class (perhaps a list subclass by the looks of it) should never be called.

Also note that if this is a list subclass, then you should use super to call the superclass:

def __getitem__(self, index):
    self._resolve()
    return super().__getitem__(index)


来源:https://stackoverflow.com/questions/27850161/what-should-i-use-instead-of-getslice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!