对列表进行子类化时,super() 是什么?如何直接访问底层列表?

jos*_*lle 0 python list subclass super superclass

class Foo(list):
    def bar(self):
        return super().__getitem__(slice(None))
    
    def baz(self):
        return super()

a = Foo([0, 1, 2, 3])
print(a.bar()) # [0, 1, 2, 3]
print(a.baz()) # <super: <class 'Foo'>, <Foo object>>

# a.bar() provides a copy of the underlying list as can be seen from the fact that each result of a.bar() has a different id
print(id(a.bar())) # id1
print(id(a.bar())) # id2 != id1
Run Code Online (Sandbox Code Playgroud)

我最近有一个用例,我需要子类化list并需要从子类 ( ) 内访问底层列表Foo。我以为super()会提供基础列表,但没有。相反,我必须super().__getitem__(slice(None))提供底层列表的副本。如何直接访问底层列表?我的理解中缺少什么super()

非常感谢!

use*_*462 5

只需使用您的实例,因为它是您的列表!

class Foo(list):
    pass


a = Foo([0, 1, 2, 3])
# __str__ method works fine
print(a)  # [0, 1, 2, 3]

for element in a:
    print(element)  # 0 1 2 3
Run Code Online (Sandbox Code Playgroud)