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?
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With