Python implements a class that returns a custom object description via the __repr__ method

Document 对象参考手册Python3 Examples

We will create a simple classPerson, and through__repr__method returns a custom description of the object.__repr__The method is typically used to generate an "official" string representation of an object, commonly used for debugging and logging.

Example

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

    def __repr__(self):
        return f"Person(name={self.name}, age={self.age})"

# Create a Person object
person = Person("Alice", 30)

# Print the description of the object
print(person)

Code analysis:

  1. __init__The method is the constructor of the class, used to initialize the object's attributes. Here, we initializednameandagetwo attributes.
  2. __repr__The method returns a string representing the "official" description of the object. In this example, we return a formatted string containing the object'snameandageattributes.
  3. We created aPersonobjectperson, and printed it. Since we defined the__repr__method, when printing, the method is called and outputs the custom description.

Output result:

Person(name=Alice, age=30)

Document 对象参考手册Python3 Examples

Other extensions