The child class inherits from the parent class. Inside the constructor of child I am initializing a list-type member variablexs by repeatedly calling the member function foo() defined in parent. It turns out that if I initialize xs by explicitly looping and appending each value returned by foo(), everything works fine.
However, if I try to do the same thing within a list comprehension, I get a strange error thrown at me. Why does this error occur? What is the difference between a list comprehension in this case, and the explicit loop?
The MWE for the code that does work:
class parent(object):
def __init__(self):
self.x = 5
def foo(self, a):
return self.x
class child(parent):
def __init__(self):
super().__init__()
self.xs = []
for i in range(9):
self.xs.append(super().foo(i))
mychild = child()
The definition of child but with the list comprehension:
class child(parent):
def __init__(self):
super().__init__()
self.xs = [super().foo(i) for i in range(9)]
The error in question:
% python test.py
Traceback (most recent call last):
File "test.py", line 20, in <module>
mychild = child()
File "test.py", line 17, in __init__
self.xs = [super().foo(i) for i in range(9)]
File "test.py", line 17, in <listcomp>
self.xs = [super().foo(i) for i in range(9)]
TypeError: super(type, obj): obj must be an instance or subtype of type
zsh: exit 1 python test.py