How to Define a Simple Python Class with __init__ and __repr__
Define a basic Python class with an __init__ method to set instance attributes and a __repr__ method for a readable representation of objects.
Python code
12 linesclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
if __name__ == "__main__":
person = Person("Alice", 30)
print(person)
Output
Person(name='Alice', age=30)
How it works
The __init__ method is the constructor that runs when a new instance is created; it assigns the passed arguments to instance attributes name and age. The __repr__ method returns a string that represents the object, ideally one that can recreate the object when evaluated. Using !r in the f-string ensures the values are formatted using their repr(), which adds quotes around strings. When you print an object, Python calls repr if __str__ is not defined, so the output shows the custom representation.
Common mistakes
- Forgetting to include `self` as the first parameter in `__init__` and other instance methods.
- Returning `None` from `__repr__` or returning a non-string value.
- Overriding `__repr__` but leaving `__str__` undefined, causing unexpected output when printing objects inside containers.
Variations
- Use dataclasses to automatically generate `__init__` and `__repr__` methods.
- Define `__str__` separately to provide a human-friendly description while keeping `__repr__` for debugging.
Real-world use cases
- Modeling domain entities like customers or employees where you need clear logs of object states.
- Debugging applications by seeing meaningful representations of objects in the debugger or error messages.
- Storing configuration objects where the repr helps verify that values were loaded correctly.
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.