Python implements a class that returns a custom object description via the __repr__ method
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)
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:
__init__The method is the constructor of the class, used to initialize the object's attributes. Here, we initializednameandagetwo attributes.__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.- We created a
Personobjectperson, 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)Other extensions
Python3 Examples