- This topic is empty.
-
AuthorPosts
-
May 16, 2026 at 1:08 am #6605
When learning Python classes, one special method you will often encounter is:
__repr__()At first glance, it may look strange because of the double underscores, but it plays a very important role in making objects readable and easier to debug.
The Example Class
Consider the following class:
class RunningEvent: """ The class models a foot race event of a length of n metres """ def __init__(self, length: int, name: str = "no name"): self.length = length self.name = name def __repr__(self): return f"{self.length} m. ({self.name})"This class models a running race event.
lengthstores the race distancenamestores the race name__repr__defines how the object should appear when displayed
What Happens Without
__repr__?Suppose we create an object:
race = RunningEvent(100, "Sprint") print(race)If the class did not define
__repr__, Python would display something like:<__main__.RunningEvent object at 0x7f2b1c4>This output represents:
- the class name
- the memory address of the object
While useful internally, it is not very human-friendly.
What
__repr__DoesNow look at this method again:
def __repr__(self): return f"{self.length} m. ({self.name})"This tells Python:
“Whenever this object is displayed, show it in this format.”
So:
race = RunningEvent(100, "Sprint") print(race)produces:
100 m. (Sprint)This is much easier to understand.
Understanding the f-string
The line:
f"{self.length} m. ({self.name})"is called an f-string.
It inserts object attributes into a string.
If:
self.length = 200 self.name = "Quarter Mile"then the returned string becomes:
"200 m. (Quarter Mile)"
Why
__repr__is UsefulThe
__repr__method helps in:- debugging programs
- printing objects clearly
- displaying lists of objects
- making classes more readable
For example:
events = [ RunningEvent(100), RunningEvent(200, "Final") ] print(events)Output:
[100 m. (no name), 200 m. (Final)]Without
__repr__, the list would display confusing memory addresses instead.
Plain English Analogy
Think of
__repr__as an object’s self-introduction.Without
__repr__:“Hi, I am object #0x7fa21…”
With
__repr__:“Hi, I am a 100 metre race called Sprint.”
Key Takeaway
The
__repr__method allows developers to control how objects appear when printed or inspected.It makes programs easier to understand and is especially valuable when working with:
- custom classes
- debugging
- lists of objects
- data models
Whenever you create your own Python classes, adding a meaningful
__repr__method is considered a good programming practice. -
AuthorPosts
- You must be logged in to reply to this topic.
