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.
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')