Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.
is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives?
You can overwrite either the
__str__or the__repr__method.There is no convention on how to implement the
__str__method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the__repr__method: it should return a string representation of the object so that the object could be recreated from that representation (if possible), i.e.eval(repr(obj)) == obj.Assuming you have a class
Point,__str__and__repr__could be implemented like this:Example: