Home > Backend Development > Python Tutorial > How Can I Customize the String Representation of My Python Class Instances?

How Can I Customize the String Representation of My Python Class Instances?

Susan Sarandon
Release: 2024-12-27 01:16:11
Original
1009 people have browsed it

How Can I Customize the String Representation of My Python Class Instances?

Custom String Representation for Class Instances

When printing instances of a class, the default output often provides only the class name and an object address. To customize this output and display specific attributes, one can define the string representation of the class.

Using str and repr Methods

Python provides two special methods, str and __repr__, that control the string representation of an object. By overriding these methods within a class, one can specify how instances of the class should appear when printed.

str Method

The str method defines the string representation to be displayed when the print function is used. It should return a string representation of the object. For example:

class Test:
    def __str__(self):
        return "member of Test"
Copy after login

repr Method

The repr method defines the string representation to be displayed when the repr() function is used or the object is inspected in the interactive prompt. It should return a string representation that can be used to recreate the object. For example:

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

Example

Consider the following example:

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

    def __str__(self):
        return str(self.a)

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

When printing an instance of this class, the following outputs will be displayed:

>>> print(Test())
foo

>>> repr(Test())
Test()
Copy after login

By defining both the str and repr methods, you have complete control over the string representation of your class instances.

The above is the detailed content of How Can I Customize the String Representation of My Python 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