我应该用什么来代替 .__getslice__? [英] What should I use instead of .__getslice__?
问题描述
我正在将一个库移植到 Python 3.我找到了这个方法:
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)
由于 .__getslice__
已弃用,因此会引发错误.我查看了文档,似乎 .__getitem__
是大多数人用来替换 .__getslice__
的东西.唯一的问题是这个库有一个与上述方法完全相同的方法,只是它被称为 __getitem__
和 listget=list.__getitem__
).我不知道他们为什么在代码中做出这种区分,但似乎库的原始设计者希望保留这两种方法的独特功能.在移植到 Python 3 时,我有什么办法可以保持这种状态吗?
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?
推荐答案
您应该能够简单地一起删除 __getslice__
方法.现在(在 python3.x 中)__getitem__
除了 __getitem__
处理的情况之外,还处理 __getslice__
过去处理的相同情况——所以,在 python3 中,不应调用自定义类上的 __getslice__
方法(从外观上看可能是列表子类).
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.
还要注意,如果这是一个列表子类,那么你应该使用super
来调用超类:
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)
这篇关于我应该用什么来代替 .__getslice__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!