Jul 28, 2013

String representation of Python objects

It is often necessary to provide string representation of the instances of different classes. Application of this can be found in debugging, dumping in a file, communication across the network, etc. Several functions in the object class of Python can be overriden to output appropriate string representations. I'm listing a few bellow:

__str__()
returns an informal string representation of an object. Does not necessarily has to be a valid python expression.

__repr__()
this function can be overriden to output a valid Python string. This is called by the builtin repr() function which, returns the python representation of an object. Since this is often used in debugging, it is suggested to be information rich.

No comments:

Post a Comment