Home > Backend Development > Python Tutorial > How to Override `__str__` and `__repr__` for Customized Print Output of Class Instances?

How to Override `__str__` and `__repr__` for Customized Print Output of Class Instances?

Susan Sarandon
Release: 2025-01-03 04:45:38
Original
502 people have browsed it

How to Override `__str__` and `__repr__` for Customized Print Output of Class Instances?

How to Customize the String Representation of Class Instances with print()

When printing instances of a class, the default behavior often displays the memory location of the object. To customize the string representation and control what is shown when printing, you can implement two special methods: str and __repr__.

__str__: Defining the Human-Readable String Representation

The str method defines the string representation of an object for general use. It is invoked when you call print() or str() on the object. By overriding __str__, you can define the custom output that is displayed when printing.

__repr__: Defining the String Representation for Debugging

The repr method defines the string representation intended for debugging purposes. It is invoked when you call repr() on the object or if you do not define str__. The __repr representation should be a valid Python expression that evaluates to the object.

Example

To customize the string representation of your class instances:

class Test:
    def __init__(self):
        self.a = 'foo'

    def __str__(self):
        return "member of Test"

    def __repr__(self):
        return "Test()"
Copy after login

In the example above:

  • The str method returns a human-readable string, "member of Test", when you print the object.
  • The repr method returns a valid Python expression, "Test()", that would recreate the object.

When you print an instance of this class:

t = Test()
print(t)
Copy after login

It will display "member of Test" on the console, providing a custom and meaningful representation.

The above is the detailed content of How to Override `__str__` and `__repr__` for Customized Print Output of Class Instances?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template