PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, September 17, 2022

[FIXED] How to print a list containing custom objects from a class?

 September 17, 2022     class, list, printing, python, repr     No comments   

Issue

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.


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']


Answered By - Vlad
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing