https://docs.python.org/ko/3/reference/datamodel.html?highlight=__repr__#object.__repr__
3. 데이터 모델 — Python 3.10.1 문서
A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define
docs.python.org
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.
요약 : 객체의 공식적인 문자열 표현을 연산하기 위한 내장 함수. __ str__대신에 쓸 수는 있지만 대신에! 쓰는 것은 추천하지는 않음. __repr__출력은 주로 문자열 관련 디버깅에서 사용하고 있다. (그래서 에러 같은 출력도 __repr__에서 진행함) return value는 무조건 string object여야 한다.
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__().
요약 : format()과 print()문 안에 있는 빌트인 함수이다. __repr__()보다 간편하며 간결한 표현을 위해 사용된다. __str__의 대체제로는 __repr__()을 사용한다. return value는 무조건 string object여야 한다.
대충 해본 예시
class Car():
def __init__(self, name, price) -> None:
self._name = name
self._price = price
def __str__(self) -> str:
return 'Car name : {}\nPrice : {}'.format(self._name, self._price)
def __repr__(self) -> str:
return 'Car name : {}\nPrice : {}'.format(self._name, self._price)