如何在 Python 中继承和扩展列表对象? [英] How to inherit and extend a list object in Python?

查看:29
本文介绍了如何在 Python 中继承和扩展列表对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用 python 列表对象感兴趣,但功能略有改变.特别是,我希望列表是 1-indexed 而不是 0-indexed.例如:

I am interested in using the python list object, but with slightly altered functionality. In particular, I would like the list to be 1-indexed instead of 0-indexed. E.g.:

>> mylist = MyList()
>> mylist.extend([1,2,3,4,5])
>> print mylist[1]

输出应该是:1

但是当我更改 __getitem__()__setitem__() 方法来执行此操作时,我收到了 RuntimeError: maximum recursion depth exceeded 错误.我对这些方法进行了大量修改,但这基本上就是我所拥有的:

But when I changed the __getitem__() and __setitem__() methods to do this, I was getting a RuntimeError: maximum recursion depth exceeded error. I tinkered around with these methods a lot but this is basically what I had in there:

class MyList(list):
    def __getitem__(self, key):
        return self[key-1]
    def __setitem__(self, key, item):
        self[key-1] = item

我想问题在于 self[key-1] 本身正在调用它定义的相同方法.如果是这样,我如何使它使用 list() 方法而不是 MyList() 方法?我尝试使用 super[key-1] 而不是 self[key-1] 但这导致了投诉 TypeError: 'type' object is unsubscriptable

I guess the problem is that self[key-1] is itself calling the same method it's defining. If so, how do I make it use the list() method instead of the MyList() method? I tried using super[key-1] instead of self[key-1] but that resulted in the complaint TypeError: 'type' object is unsubscriptable

有什么想法吗?另外,如果你能指点我一个很好的教程,那就太好了!

Any ideas? Also if you could point me at a good tutorial for this that'd be great!

谢谢!

推荐答案

使用super()函数调用基类的方法,或者直接调用方法:

Use the super() function to call the method of the base class, or invoke the method directly:

class MyList(list):
    def __getitem__(self, key):
        return list.__getitem__(self, key-1)

class MyList(list):
    def __getitem__(self, key):
        return super(MyList, self).__getitem__(key-1)

然而,这不会改变其他列表方法的行为.例如,索引保持不变,这可能会导致意想不到的结果:

However, this will not change the behavior of other list methods. For example, index remains unchanged, which can lead to unexpected results:

numbers = MyList()
numbers.append("one")
numbers.append("two")

print numbers.index('one')
>>> 1

print numbers[numbers.index('one')]
>>> 'two'

这篇关于如何在 Python 中继承和扩展列表对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆