如何创建一个也是列表的类?

juk*_*mil 7 python

我想用Python创建一个具有各种属性和方法的类,但是为了继承列表的功能,我可以将对象追加到对象本身,而不是任何属性.我希望能够说' graph[3]',而不是' graph.node_list[3]'.有没有办法做到这一点?

Nig*_*een 10

你真正需要做的就是提供一个 __getitem__

In [1]: class Foo:
   ...:     def __init__(self, *args):
   ...:         self.args = args
   ...:     def __getitem__(self, i):
   ...:         return self.args[i]
   ...:     

In [2]: c = Foo(3,4,5)

In [3]: c[2]
Out[3]: 5

In [4]: c[3]
IndexError: tuple index out of range #traceback removed for brevity

In [5]: for i in c: print(i) #look, ma, I can even use a for-loop!
3
4
5
Run Code Online (Sandbox Code Playgroud)

附录:您可能还想提供其他方法.__len__绝对是其中之一.有一个相当长的魔术方法列表,我建议通过它们并选择有意义的方法.


o11*_*11c 5

你可以继承自list:

class Foo(list):
    def __init__(self):
        pass
Run Code Online (Sandbox Code Playgroud)

但是对内置类型进行子类化并不一定是个好主意.


collections.abc.Sequence(或从3.5开始typing.Sequence[T])就是我这样做的方式.