Tuesday, 18 February 2014

Gotchas about __str__ and __repr__

Many of python developers confused with the gotcha of __str__ and __repr__ in-built function of python.

So lets's try to clear this.

For new beginners

  • __str__ can be treated as informal string representation of an object.
  • __repr__ can be taken as formal representation of an object
Confused!! :P
No need to worry, lets take help of lovable python terminal. 

Consider an example of number


As from the above result str() and repr() are same.

Now consider an example of string


From above results its clear that while evaluating result of str & repr are different and not valid in case of str representation of a string
Hope now its clear.
Reactions:

0 comments:

Post a Comment