Stringify class


  • __repr__ "should" return Python-like code
  • __str__ should return readable representation
  • If __str__ does not exist, __repr__ is called instead.


examples/oop/stringification/shapes.py

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)


examples/oop/stringification/run.py

import shapes

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