Python implement a class whose repr method returns a custom object description
We will create a simple class Personand use the __repr__ method to return a custom description of the object.__repr__ The method is usually used to produce the "official" string representation of an object, typically 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 object description
(
person
)
Code analysis:
__init__method is the class constructor, used to initialize the object's attributes. Here we initializenameandagetwo attributes.__repr__The method returns a string that is the "official" description of the object. In this example we return a formatted string containing the object'snameandageattribute.- We created a
Personobjectpersonand printed it. Because we defined the__repr__method, printing calls that method and outputs the custom description.
Output result:
Person(name=Alice, age=30)
Python3 Examples