You can overwrite either the __str__ function or __repr__ .
There is no agreement on how to implement the __str__ function; it can simply return any readable representation of the string you want. However, there is an agreement on how to implement the __repr__ function: it must return a string representation for the object so that the object can be recreated from this representation (if possible), i.e. eval(repr(obj)) == obj .
Assuming you have a Point class, __str__ and __repr__ can be implemented as follows:
class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(%.2f, %.2f)" % (self.x, self.y) def __repr__(self): return "Point(x=%r, y=%r)" % (self.x, self.y) def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y
Example:
>>> p = Point(0.1234, 5.6789) >>> str(p) '(0.12, 5.68)' >>> "The point is %s" % p
source share