如何打印包含类中自定义对象的列表?
我开始学习 Python 中的 OOP。我有一个像这样的简单问题。例如,我有一个名为 Cat 的类,以及一个名为 ListOfCat 的类,其中包含 Cat 列表。现在我想打印猫列表。下面是我的代码:
class Cat:
def __init__(self,name,color):
self.name = name
self.color = color
def __repr__(self):
return '{} {}'.format(self.name,self.color)
class ListOfCat:
list_of_cat=[]
def add_cat(self,cat):
self.list_of_cat.append(cat)
def __repr__(self):
pass #Need something here
Cat1 = Cat('Lulu','red')
Cat2 = Cat('Lala','white')
List1 = ListOfCat()
List1.add_cat(Cat1)
List1.add_cat(Cat2)
print(List1) #TypeError: __str__ returned non-string (type NoneType)
#Expected output: ['Lulu red','Lala white']
for cat in List1.list_of_cat: #I found this method on the internet but the result isn't what I want
print(cat)
#Lulu red
#Lala white
如果有人能告诉我在 pass
行中输入什么内容,我真的很感激。
I'm starting to learn about OOP in Python. I have a simple problem like this. For example, I have a class called Cat, and a class called ListOfCat which contains a List of Cat. Now I want to print the List Of Cat. Below is my code:
class Cat:
def __init__(self,name,color):
self.name = name
self.color = color
def __repr__(self):
return '{} {}'.format(self.name,self.color)
class ListOfCat:
list_of_cat=[]
def add_cat(self,cat):
self.list_of_cat.append(cat)
def __repr__(self):
pass #Need something here
Cat1 = Cat('Lulu','red')
Cat2 = Cat('Lala','white')
List1 = ListOfCat()
List1.add_cat(Cat1)
List1.add_cat(Cat2)
print(List1) #TypeError: __str__ returned non-string (type NoneType)
#Expected output: ['Lulu red','Lala white']
for cat in List1.list_of_cat: #I found this method on the internet but the result isn't what I want
print(cat)
#Lulu red
#Lala white
I really appreciate it if someone could tell me what to type in the pass
line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有很多方法可以做到这一点。这是一个:
输出:
There are many ways you could do this. Here's one:
Output:
我想上面的答案已经回答了你的问题。但我想补充一点,您只需输入
print(List1.list_of_cat)
也可以。I think the above answer answered your question. But I want to add that you can just type
print(List1.list_of_cat)
also work too.