How to Define a Simple Class with __init__ and __repr__ in Python
Defines a Person class with __init__ to store name and age, and __repr__ to give a readable string representation.
Python code
14 linesclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
if __name__ == "__main__":
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1)
print(p2)
Output
Person(name='Alice', age=30)
Person(name='Bob', age=25)
How it works
The __init__ method runs automatically when an instance is created, setting the name and age attributes. The __repr__ method returns a string that, if possible, should look like a valid Python expression that recreates the object — this helps in debugging and logging. When you print an object, Python calls __repr__ (or __str__ if defined) to display it. Here, the f-string formats the attributes into a clear, readable format.
Common mistakes
- Forgetting to pass `self` as the first parameter to `__init__`.
- Using `__str__` instead of `__repr__` when you want a developer-friendly representation.
- Not returning a string from `__repr__` — it must return a string.
Variations
- Use a dataclass to automatically generate __init__ and __repr__: `@dataclass` class Person.
- Override __str__ separately for user-facing output while keeping __repr__ for debugging.
Real-world use cases
- Defining model classes in an ORM like SQLAlchemy to represent database rows and log instances clearly.
- Creating small value objects in a domain model whose instances are compared in logs and error messages.
- Building a simple configuration object whose string representation aids debugging in a CLI tool.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.