SoFunction
Updated on 2025-04-07

Detailed explanation of the usage examples of magic methods __repr__ and __str__ in Python

introduction

When we print a python class object directly, we usually get something like "<main.ClassName object at 0xmemory_address>" cannot obtain the specific state of the object. At this time, we can redefine/rewrite the magic method of the corresponding class__repr__and__str__, enables us to obtain the current status information of the object when printing it.

1. __repr__ method

1.1 Meaning and Function

In Python,__repr__Method is a special method, with its full name "representation", that is, "representation" or "expression". This method is used to return an object's "official" string representation, mainly used for debugging and development purposes, so that developers can clearly see the object's state.

1.2 Example

Here is a simple example to illustrate__repr__How to use:

class Point:
    def __init__(self, x, y):
         = x
         = y

    def __repr__(self):
        return f'Point(x={}, y={})'

p = Point(1, 2)
  
# This example defines the `__repr__` method# Output: Point(x=1, y=2)print(p)

# If the `__repr__` method is not defined,# The output may be: <__main__.Point object at 0x7fecf006e978>

In this example, the Point class defines a__repr__Method: When object p is printed, Point(x=1, y=2) will be output, so that the position information of the point is clearly displayed.

2. __str__ method

2.1 Meaning and function

In Python,__str__Methods are also a special method (also known as magic method) that defines how objects are converted to user-friendly string representations. When an object is printed (passed to the print() function) or converted to a string type (such as using str(obj)), the Python interpreter will try to call the object's__str__method.

__str__The method provides an object with a concise and easy-to-read string representation, which is very user-friendly, so that developers and end users can understand the real-time state of the object, and is usually used for debugging and logging.

2.2 Example

Here is a simple example showing how to define it__str__Method to describe an object of a Person class:

class Person:
    def __init__(self, name, age):
         = name
         = age

    def __str__(self):
        return f"{} is {} years old."
    
# Create a Person instancejohn = Person('John Doe', 30)

# Print this Person instanceprint(john)  # Output: John Doe is 30 years old.
# Convert an object to a stringperson_str = str(john)
print(person_str)  # Output: John Doe is 30 years old.

In this example,__str__The method returns a formatted string, describingPersonThe name and age of the object. When we willjohnWhen an object is printed or converted to a string,__str__The method will be called automatically, thus returning the descriptive string we defined.

If a class is not defined__str__Methods, Python interpreter will call built-in__repr__Method to get the string representation of the object. If there is no definition__repr__Method, the Python interpreter will use the default string representation, that is, return the actual address of the object in computer memory.

3. Comparison of the two methods

Both methods start and end with two underscores, and this naming method is a convention used by Python to identify special methods.

__repr__(representation): The main purpose is to provide the interpreter and the developer with the details of the object. It should return a string containing all the information needed to create this object. Ideally, the string can be recreated with python code.

__str__(stringification): The main purpose is to provide a humanized string representation for objects, which is convenient for developers and users to understand the state of objects. Its results should be concise and intuitive and easy to read.

Here is an example to further illustrate the difference between the two:

class Person:
    def __init__(self, name, age):
         = name
         = age

    def __repr__(self):
        # Return a string that can be executed directly by eval()        return f"Person('{}', {})"

    def __str__(self):
        return f"{} is {} years old."

# Create a Person instancejohn = Person('John Doe', 30)

# Use the repr function to display the official string representation of the objectprint(repr(john))  # Output: Person('John Doe', 30)
# Use the eval() function to recreate the object based on the string provided by `__repr__`new_john = eval(repr(john))

# Check whether the new object has the same attribute value as the original objectprint(new_john)  # Output: John Doe is 30 years old.print(new_john.name, new_john.age)  # Output: John Doe 30

In this example, the __repr__ method provides a string that can be used to recreate a Person object, which can be executed by the eval() function to create a new Person instance. and__str__The method provides a humanized description for the Person object.

Overall,__repr__The purpose of the method is to represent the state of the object as accurately as possible so that developers can accurately understand the internal data of the object. In contrast,__str__The method tends to be user-friendly display. In actual programming, it is recommended to define both methods at the same time to ensure that the object can get the appropriate string representation in all contexts.

Difference summary:

Both __repr__ and __str__ are used for display. __str__ is for users, and __repr__ is for programmers.

  • The print operation will first try the __str__ and str built-in functions (the internal equivalent form of print run), which should usually return a friendly display.

  • __repr__ is used in all other environments: used for prompt responses in interactive mode and repr function. If __str__ is not used, print and str will be used. It should usually return an encoded string that can be used to recreate the object or display it in detail to the developer.

When we want to display uniformly in all environments, we can refactor the __repr__ method; when we want to support different displays in different environments, for example, end user display uses __str__, while programmers use the underlying __repr__ to display during development. In fact, __str__ just overwrites __repr__ to get a more friendly user display.

Summarize

This is the article about the usage of magic methods __repr__ and __str__ in Python. For more related Python magic methods __repr__ and __str__, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!