본문 바로가기

참고문서(번역?)

__repr__() vs. __str__()

Python에는 문자열관련 special method가 두개가 있습니다.

__str__()과 __repr__()

[공식문서의 내용을 볼까요?]

__repr__()

object.__repr__(self)

Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required. 

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

 내장함수 repr()에 의해 호출되며 객체의 "공식적인" 문자열 표현을 계산한다. 이 문자열은 유효한 파이썬 표현식처럼 보이고 (적절한 환경이 주어지면) 같은 값을 가진 객체를 재생성하는데 사용할 수 있다. 만일 재생성이 불가능하다면, <...어떤 유효한 설명...> 같은 형태의 문자열이 반환되어야 한다. 클래스를 구현할 때 __repr__()을 구현하고 __str__()을 구현하지 않으면 그 클래스 인스턴스의  "비공식" 문자 표현이 필요한 경우 __repr__()이 사용된다.

__str__()

 object.__str__(self)

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.

The default implementation defined by the built-in type object calls object.__repr__().

 str(object)와 내장 함수 format()과 print()에 의해 호출되며 객체의 "비공식" 또는 인쇄하기 좋은 문자열 표현을 계산한다. 반환되는 값은 문자열 객체이다.

내장 타입 object에 의해 기본적으로 object.__repr__()을 호출하도록 구현되어 있다.


그러면 어떻게 하면 될까요?

클래스를 구현할 때 일단 __repr__()은 구현하자. eval(repr(...))을 하면 파이썬 객체를 생성할 수 있도록...


'참고문서(번역?)' 카테고리의 다른 글

10분만에 끝내는 pandas  (0) 2017.10.01
__slots__  (0) 2017.07.06
PEP 3102 -- Keyword-Only Arguments  (0) 2017.07.04