__repr__ vs __str__ in Python

Tags:

http://www.eros-os.org/pipermail/e-lang/2002-June/006813.html

here are two standard ways of converting an object to a string in
Python.

One is repr(), which produces output suitable for a REPL; in
particular, it unambiguously identifies the type of the object, and if
possible, it is a syntactically-valid Python expression which, if
evaluated, would produce an object equal to the object originally
passed to repr().

[..]

The other is str(), whose purpose is to make sure that something is a
string so you can print it. It calls repr() if there is no str()
defined for the object, but some objects define different repr() and
str() behavior. In particular, str(x) == x if x is already a string.

I think this is a very pleasant distinction to have. It allows
objects to be both readably serialized and clearly displayed by
recognizing the difference in intent. JavaScript’s conversion to
string fails badly for many things, such as arrays of empty strings,
mostly because JavaScript does not have a way to recognize this
difference.

본문에 REPL이라는 건 Read Evaluate Print Loop 의 약자라고 하는군요. 그리고 __str__ 이 정의 안되면 자동으로 __repr__로 delegate됨. __repr__이라는건, representation을 의미

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *