class Fruit: def __init__(self, name): self.name = name def __str__(self): return f"Fruit: {self.name}" def __repr__(self): return f"Fruit('{self.name}')" f = Fruit('Apple') print(str(f)) print(repr(f))
The str() function calls __str__ which returns 'Fruit: Apple'. The repr() function calls __repr__ which returns 'Fruit('Apple')'.
class Animal: def __init__(self, species): self.species = species def __repr__(self): return f"Animal('{self.species}')" animals = [Animal('Cat'), Animal('Dog')] print(animals)
When printing a list, Python calls __repr__ on each element. So it shows the string returned by __repr__ of each Animal.
class Book: def __init__(self, title): self.title = title def __str__(self): return 'Book title is ' + self.title.upper b = Book('Python 101') print(b)
The error happens because self.title.upper is a method, not a string. You must call it with parentheses: self.title.upper().
__str__ and __repr__ methods in Python?__str__ returns a friendly string for users, while __repr__ returns a detailed string useful for developers to identify the object.
class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" p = Point(3, 4) q = eval(repr(p)) print(p == q) print(q)
The repr returns 'Point(3, 4)', but eval tries to call Point(3, 4). Since Point constructor exists, q is a new object with same values but different identity. The default == compares identity, so p == q is False.
