Reputation: 13
I am wondering how to print attribute(which is a list of another class) of a class one item in row. The code looks something like this:
class A:
def __init__(self, i):
self.index = i
def __str__(self):
return str(self.index)
__repr__ = __str__
class B:
def __init__(self):
self.b = []
def load(self):
for i in range(3):
a = A(i)
self.b.append(a)
def __str__(self):
# My 1st solution
return self.b
# My 2nd solution
for i in self.b:
print(i)
__repr__ = __str__
b = B()
b.load()
print(b) # TypeError: __str__ returned non-string (type list)
Expected output:
0
1
2
Upvotes: 1
Views: 66
Reputation: 6518
You can do something like this:
def __str__(self):
return '\n'.join([str(x) for x in self.b])
Which would make each <class '__main__.A'>
inside self.b
into a str
before joining them with .join
.
>>> print(b)
0
1
2
Upvotes: 1