__str__ and __repr__
noun
say it: “DUN-der STUR and DUN-der REP-er” /ˈdʌndər ˈstɝ ənd ˈdʌndər ˈrɛpər/
Two methods a class can write: __str__ sets how an object looks when printed for users, and __repr__ the more detailed text developers see while debugging.
What do __str__ and __repr__ do?
__str__ sets what an object looks like when printed for users. __repr__ sets the more detailed version developers see while debugging.
class Product:
def __init__(self, name, price):
self.name, self.price = name, price
def __str__(self):
return f"{self.name} (${self.price})"
print(Product("Lamp", 25)) # Lamp ($25)
In a sentence
- “The debugger shows each product through its __repr__ method.”
- “With __str__, print(lamp) shows Lamp ($25) instead of a memory address.”
Level: Journeyman · More Python terms at this level
Updated