Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading