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.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 9 views 0 copies

Python code

14 lines
Python 3.9+
class 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

stdout
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

  1. Use a dataclass to automatically generate __init__ and __repr__: `@dataclass` class Person.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.