Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Class Whose __repr__ Method Returns a Custom Object Description

Python implement a class whose repr method returns a custom object description

Document Object Reference Manual Python3 Examples

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

print

(

person

)

Code analysis:

  1. __init__ method is the class constructor, used to initialize the object's attributes. Here we initialize name and age two attributes.
  2. __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's name and age attribute.
  3. We created a Person object personand printed it. Because we defined the __repr__ method, printing calls that method and outputs the custom description.

Output result:

Person(name=Alice, age=30)

Document Object Reference Manual Python3 Examples