Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a list of objects of user defined class

Tags:

python

So I have a class, called Vertex.

class Vertex:     '''     This class is the vertex class. It represents a vertex.     '''      def __init__(self, label):         self.label = label         self.neighbours = []      def __str__(self):         return("Vertex "+str(self.label)+":"+str(self.neighbours)) 

I want to print a list of objects of this class, like this:

x = [Vertex(1), Vertex(2)] print x 

but it shows me output like this:

[<__main__.Vertex instance at 0xb76ed84c>, <__main__.Vertex instance at 0xb76ed86c>] 

Actually, I wanted to print the value of Vertex.label for each object. Is there any way to do it?

like image 367
czardoz Avatar asked Oct 17 '12 12:10

czardoz


People also ask

How do you print an object list in Python?

Printing a list in python can be done is following ways: Using for loop : Traverse from 0 to len(list) and print all elements of the list one by one using a for loop, this is the standard practice of doing it.

How do you print all objects in a class Python?

To print all instances of a class with Python, we can use the gc module. We have the A class and we create 2 instances of it, which we assigned to a1 and a2 . Then we loop through the objects in memory with gc. get_objects with a for loop.

How do you create a list of objects in a class?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.

What the __ repr __ function does?

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.


1 Answers

If you just want to print the label for each object, you could use a loop or a list comprehension:

print [vertex.label for vertex in x] 

But to answer your original question, you need to define the __repr__ method to get the list output right. It could be something as simple as this:

def __repr__(self):     return str(self) 
like image 52
Daniel Roseman Avatar answered Sep 19 '22 20:09

Daniel Roseman