Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Stringify class

  • str

  • repr

  • repr "should" return Python-like code

  • str should return readable representation

  • If str does not exist, repr is called instead.

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
       return 'Point({}, {})'.format(self.x, self.y)

    def __str__(self):
       return '({}, {})'.format(self.x, self.y)
import shapes

p1 = shapes.Point(2, 3)
print(repr(p1)) # Point(2, 3)
print(str(p1))  # (2, 3)
print(p1)       # (2, 3)