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.

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

Python code

12 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!r}, age={self.age!r})"


if __name__ == "__main__":
    person = Person("Alice", 30)
    print(person)

Output

stdout
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

  1. Use dataclasses to automatically generate `__init__` and `__repr__` methods.
  2. 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

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.