如何打印包含来自 class 的自定义对象的列表?

How to print a list containing custom objects from a class?

我在 Python 开始学习 OOP。我有一个像这样的简单问题。例如,我有一个名为 Cat 的 class 和一个名为 ListOfCat 的 class,其中包含一个 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 行中输入什么,我将不胜感激。

有很多方法可以做到这一点。这是一个:

class Cat:
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
    def __repr__(self):
        return f"'{self.name} {self.colour}'"

class ListOfCats:
    def __init__(self):
        self.loc = []
    def addcat(self, cat):
        self.loc.append(cat)
    def __repr__(self):
        return str(self.loc)

LOC = ListOfCats()

LOC.addcat(Cat('Lulu', 'red'))
LOC.addcat(Cat('Lala', 'white'))

print(LOC)

输出:

['Lulu red', 'Lala white']

我认为上面的回答回答了你的问题。但我想补充一点,您只需输入 print(List1.list_of_cat) 也可以。