Printing a List of Objects of User Defined Class

Printing a list of objects of user defined class

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)

How to print instances of a class using print()?

>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

How to print() an object in list in Python

Turn your list_student function into a __repr__ method on Student:

class Student:
def __init__(self, std_id, std_name, std_dob, std_mark=0):
self.student_id = std_id
self.student_name = std_name
self.student_dob = std_dob
self.student_mark = std_mark

def __repr__(self):
return (
f"ID: {self.student_id}\n"
f"Name: {self.student_name}\n"
f"Dob: {self.student_dob}\n"
f"GPA: {self.student_mark}\n"
)

Now any time you print a Student (even in a list), you'll get a string with that formatting instead of the default <__main__.Student object at xxxxx> one.

Printing a list containing user defined objects returns addresses and implementing roots of complex numbers in python

You need to implement __repr__() in your complex class. While str() is used specifically when converting to a string, repr() is used in most other cases where you're printing an object. It could be as simple as

def __repr__(self):
return str(self)

which will leave the repr looking the same as the string. Alternatively, you might want to make it more explicit in the repr that this is a complex number than just printing it, in which case you might do

def __repr__(self):
return f"complex({str(self)})"

or something similar. It's up to you in how you want to handle it.

How can i print the attributes of an object list that stores objects?

Implement __str__ or __repr__ for Dog so Python knows how to represent it.

class Dog:
def __init__(self, name, age):
self.__name = name
self.__age = age
def __repr__(self):
return f"Dog({self.__name}, {self.__age})"
def __str__(self):
return f"Woof! I'm {self.__name}, and I'm {self.__age} years old!"

More information about __str__ and __repr__ can be found here

How to apply __str__ function when printing a list of objects in Python

Try:

class Test:
def __repr__(self):
return 'asd'

And read this documentation link:



Related Topics



Leave a reply



Submit