2.7.2 Print Representation

The standard Python printing method is __repr__(self). In Sage, that is for objects that derive from SageObject (which is everything in Sage), instead define _repr_(self). This is preferable because if you only define _repr_(self) and not __repr__(self), then users can rename your object to print however they like.

Here is an example of the _latex_ and _repr_ functions for the Pi class. It is from the file SAGE_ROOT/devel/sage/sage/functions/constants.py

%skip
class Pi(Constant):
    """
    The ratio of a circle's circumference to its diameter.

    EXAMPLES:
        sage: pi
        pi
        sage: float(pi)
        3.1415926535897931
    """
        ...
    def _repr_(self):
        return "pi"

    def _latex_(self):
        return "\\pi"

See About this document... for information on suggesting changes.