Home > Software design >  How to print a list containing custom objects from a class?
How to print a list containing custom objects from a class?

Time:03-04

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.

CodePudding user response:

There are many ways you could do this. Here's one:

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)

Output:

['Lulu red', 'Lala white']

CodePudding user response:

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.

  • Related