Implement readable and developer-facing object representations.
How It Works
__str__() produces a user-friendly string when str() is called; __repr__() supports developer inspection and ideally gives an unambiguous form. If __str__ is absent, str() falls back to __repr__().
Dataclasses can generate a useful __repr__ automatically.
Step-by-Step Example
class Product:
def __init__(self, product_name):
self.product_name = product_name
def __str__(self):
return self.product_name
def __repr__(self):
return f"Product({self.product_name!r})"
product = Product("Notebook")
print(str(product))
print(repr(product))
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
Notebook
Product('Notebook')
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Add both methods to a small Account object and compare their outputs.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Returning something other than str from __str__() or __repr__().
- Leaking secret tokens or credentials inside debug representations.
Key Takeaways
- Implement readable and developer-facing object representations.
- __str__() produces a user-friendly string when str() is called; __repr__() supports developer inspection and ideally gives an unambiguous form.
- Dataclasses can generate a useful __repr__ automatically.