Senger CodeLab 🚀

How do I change the string representation of a Python class duplicate

September 29, 2026

How do I change the string representation of a Python class duplicate

Representing your Python classes in a human-readable way is crucial for debugging, logging, and generally making your code easier to understand. You might be used to seeing something like <__main__.MyClass object at 0x...> when you print a class instance. This default representation isn’t very informative. Fortunately, Python offers elegant ways to customize how your classes appear as strings, giving you control over the information displayed. This article will explore the core methods, __str__ and __repr__, and demonstrate how to use them effectively to create informative and user-friendly string representations of your objects.

Understanding __str__

__str__ is the method Python calls when you use the str() function on your object or when you use the print() function. It’s designed for creating a user-friendly, easily readable string representation. Think of it as the informal introduction of your object.

For example, if you have a Dog class, the __str__ method might return a string like “Fido the Golden Retriever”.

Here’s how you’d implement it:

class Dog: def __init__(self, name, breed): self.name = name self.breed = breed def __str__(self): return f"{self.name} the {self.breed}" 

Understanding __repr__

__repr__ is intended to produce a more technical, unambiguous string representation. Ideally, the string returned by __repr__ should be valid Python code that could be used to recreate the object. This is particularly useful for debugging. Python calls __repr__ when you simply type the object’s name in the interactive interpreter or when you use the repr() function.

For the Dog class, a good __repr__ might look like this:

def __repr__(self): return f"Dog(name='{self.name}', breed='{self.breed}')" 

This clearly shows how the object was constructed.

Best Practices for __str__ and __repr__

While you can technically use either method interchangeably, following these best practices will make your code more robust and maintainable:

  • Always implement __repr__. Even if you don’t anticipate needing a detailed representation, it’s a good habit and helps with debugging. If you only implement one, make it __repr__.
  • Make __str__ user-friendly. Focus on the most important information. Avoid overly technical details.
  • Ensure __repr__ is as unambiguous as possible. Include enough information to recreate the object.

Practical Example: Customizing a Point Class

Let’s illustrate with a Point class representing a 2D coordinate:

class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"({self.x}, {self.y})" def __repr__(self): return f"Point(x={self.x}, y={self.y})" 

This provides both a concise string representation for printing and a more detailed one for debugging.

Place infographic demonstrating the difference in output between __str__ and __repr__.

Key Differences Summarized

  1. Purpose: __str__ for user-friendly output, __repr__ for unambiguous representation.
  2. Fallback: If __str__ isn’t defined, Python falls back to __repr__.
  3. Usage: str() and print() use __str__; repr() and interactive interpreter use __repr__.

Implementing these methods empowers you to represent your Python class objects effectively in your code, making it more readable, debuggable, and maintainable. By following best practices and understanding the nuances of __str__ and __repr__, you can create robust and user-friendly string representations for your custom classes.

A well-crafted string representation can greatly improve the developer experience when working with your classes. It helps in debugging, logging, and understanding the state of objects at a glance. This becomes even more crucial when dealing with complex data structures or in interactive development environments. By investing a little effort in implementing __str__ and __repr__ effectively, you contribute significantly to the readability and maintainability of your Python code. Explore more on object representation in Python’s official documentation here and discover advanced techniques for customizing string output. Also, check out this helpful guide on Stack Overflow: Difference between __str__ and __repr__. Deepen your understanding of Python’s data model with this in-depth article here. Consider experimenting with these methods in your own projects and discover how they can improve your workflow. Learn more about effective debugging strategies by exploring advanced debugging techniques.

FAQ:

Q: What if I only define __repr__?

A: Python will use __repr__ for both str() and repr() calls.

  • __str__ prioritizes readability.
  • __repr__ prioritizes unambiguous representation.

Question & Answer :

In Java, I can override the `toString()` method of my class. Then Java's print function prints the string representation of the object defined by its `toString()`. Is there a Python equivalent to Java's `toString()`?

For example, I have a PlayCard class. I have an instance c of PlayCard. Now:

>>> print(c) <__main__.Card object at 0x01FD5D30> 

But what I want is something like:

>>> print(c) A♣ 

How do I customize the string representation of my class instances?

I’m using Python 3.x

The closest equivalent to Java’s toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self): return "foo" 

You may also want to implement __repr__ to aid in debugging.

See here for more information: