17.6: The __str__ method

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    17.6: The __str__ method

    __str__ is a special method, like __init__, that is supposed to return a string representation of an object.

    For example, here is a str method for Time objects:

    # inside class Time:
    
        def __str__(self):
            return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
    

    When you print an object, Python invokes the str method:

    >>> time = Time(9, 45)
    >>> print(time)
    09:45:00
    

    When I write a new class, I almost always start by writing __init__, which makes it easier to instantiate objects, and __str__, which is useful for debugging.

    As an exercise, write a str method for the Point class. Create a Point object and print it.


    This page titled 17.6: The __str__ method was last modified on Tue, 01 Dec 2020 03:30:53 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.