Python – repr VS str


class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        
    def area(self):
        return self.width * self.height
    
    def perimeter(self):
        return 2 * (self.width + self.height)
    
    def __str__(self):
        return 'Rectangle (width={0}, height={1})'.format(self.width, self.height)
    
    def __repr__(self):
        return 'Rectangle({0}, {1})'.format(self.width, self.height)
r1 = Rectangle(10, 20)
print(r1)  # uses __str__
Rectangle (width=10, height=20)
r1  # uses __repr__
Rectangle(10, 20)

Fermer le menu