'Print Class variable that's a list with a Classmethod using __str__?
I'm taking a course in Python, and my task is to print a defined class variable, a list containing all objects of my class, as a formated table using the instance method str
I have no idea how to do this. I did manage to get one object as the output but my output doesn't print all the objects in the list. I tried using a for loop inside the classmethod, but I can still only put one line as the return statement.
Here's my code:
class Person:
obj = []
def __init__(self, name, lastname, age):
self.name = name
self.lastname = lastname
self.age = age
self.obj.append(self)
def __str__(self):
print("{:<12} {:<15} {:<10}".format ('Name', 'Last name', 'Age'))
return "{:<12} {:<15} {:<10}".format (self.name, self.lastname, self.age)
@classmethod
def info_people(cls):
for i in cls.obj:
str(i).__str__()
return str(i).__str__()
p1 = Person('Erwin', 'Smith', 34)
p2 = Person('James', 'Porter', 23)
p3 = Person('Madison', 'Stewart', 45)
p4 = Person('Hanna', 'Stark', 14)
p5 = Person('Tina', 'Liu', 6)
print(Person.info_people())
(This was the output)
Name Last name Age
Name Last name Age
Name Last name Age
Name Last name Age
Name Last name Age
Name Last name Age
Tina Liu 6
Solution 1:[1]
You can use str.join() and map() functions to construct the string to print. For example:
class Person:
obj = []
def __init__(self, name, lastname, age):
self.name = name
self.lastname = lastname
self.age = age
self.obj.append(self)
def __str__(self):
return "{:<12} {:<15} {:<10}".format(self.name, self.lastname, self.age)
@classmethod
def info_people(cls):
out = "{:<12} {:<15} {:<10}\n".format("Name", "Last name", "Age")
out += "\n".join(map(str, cls.obj))
return out
p1 = Person("Erwin", "Smith", 34)
p2 = Person("James", "Porter", 23)
p3 = Person("Madison", "Stewart", 45)
p4 = Person("Hanna", "Stark", 14)
p5 = Person("Tina", "Liu", 6)
print(Person.info_people())
Prints:
Name Last name Age
Erwin Smith 34
James Porter 23
Madison Stewart 45
Hanna Stark 14
Tina Liu 6
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrej Kesely |
