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
I recently had a use case where I needed to subclass list
and needed to access the underlying list from within the subclass (Foo
). I thought super()
would provide the underlying list, but it didn't. Instead I had to do super().__getitem__(slice(None))
which provides a copy of the underlying list. How do I access the underlying list directly? And what am I missing in my understanding of super()
?
Many thanks!
CodePudding user response:
Just use your instance, as it's your list!
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