0
class A():
    def __init__(self,x):
         self.x = x 
    def __repr__(self):
         return self.x

For example, if I have a statement like A("one"), the output is one. Therefore, can I assume that repr is invoked every time when I create a new instance of the class?

henrywongkk
  • 1,840
  • 3
  • 17
  • 26
BigBro666
  • 71
  • 8
  • _"Therefore, can I assume that repr is invoked every time when I create a new instance of the class?"_ > No, it is not. And I am curious how to come up with this conclusion – Adrian Shum Oct 23 '19 at 02:20

1 Answers1

1

__str__ is used for creating output for end user while __repr__ is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable.

A good exemple

import datetime 
today = datetime.datetime.now() 

# Prints readable format for date-time object 
print str(today) 

# prints the official format of date-time object 
print repr(today)  

will output

2016-02-22 19:32:04.078030
datetime.datetime(2016, 2, 22, 19, 32, 4, 78030)
JeanMGirard
  • 171
  • 2
  • 7