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

Change the object preview into one of its own attributes

i have a list that contain some objects. when i print the list i see the adress of the objects.

print(lst)
>>> [<__main__.pokemon object at 0x7f9780554b80>, <__main__.pokemon object at 0x7f9780554bb0>, <__main__.pokemon object at 0x7f9780554be0>]

I want change the preview of each object into specifice attribute .(e.g: obj.name) but without print obj.name for each index in the list.

so if i just print the object name it will print the whole object.
like in this code.

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

print(lst)
>>> [Jhon,Ben,Dan]
print(Ben)
>>> <__main__.pokemon object at 0x7f9780554bb0>

>Solution :

Override the __repr__ method of your class:

# PEP8: Class names should normally use the CapWords convention.
class Pokemon():

     def __init__(self, name):
         self.name = name

     def __repr__(self):
         return f"Pokemon(name='{self.name}')"

Usage:

p = Pokemon('Pikachu')
print(p)

# Output
Pokemon(name='Pikachu')
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