使用 __str__ 打印带有类方法列表的类变量?
我正在学习Python课程,我的任务是打印一个定义的类变量,一个包含我的类的所有对象的列表,作为使用实例方法 str 的格式化表,
我不知道如何来做到这一点。我确实设法获得一个对象作为输出,但我的输出没有打印列表中的所有对象。我尝试在类方法中使用 for 循环,但我仍然只能将一行作为 return 语句。
这是我的代码:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
str.join()
和map()
函数来构造要打印的字符串。例如:打印:
You can use
str.join()
andmap()
functions to construct the string to print. For example:Prints: