1. 문자열 표현
__repr__() 특별 메서드는 객체를 문자열로 표현하기 위해 repr() 내장 메서드에 의해 호출된다. __repr__() 메서드가 반환한 문자열은 명확해야 하며, 가능하면 표현된 객체를 재생성하는 데 필요한 소스 코드와 일치해야 한다.
__repr__()와 __str__()을 비교하면, __str__() 메서드는 str() 생성자에 의해 호출되며 print()에 의해 암묵적으로 사용된다. __str__()은 사용자에게 보여주기 적당한 형태의 문자열을 반환해야 한다.
이 두 메서드 중 하나만 구현해야 하면 __repr__() 메서드를 구현하는 것을 추천한다. 파이썬 인터프리터는 __str__() 메서드가 구현되어 있지 않을 때의 대책으로 __repr__() 메서드를 호출하기 때문이다.
특별 메서드
문자열/바이트 표현 : __repr__, __str__, __format__, __bytes__
숫자로 변환 : __abs__, __bool__, __complex__, __init__, __float__, __hash__, __index
컬렉션 어뮬레이션 : __len__, __getitem__, __setitem__, __delitem__, __contains__
반복 : __iter__, __reversed__, __next__
콜러블 에뮬레이션 : __call__
콘텍스트 관리 : __enter__, __exit__
객체 생성 및 소멸 : __new__, init__, __del__
속성 관리 : __getattr__, __getattribute__, __setattr__, __delattr__, __dir__
속성 디스크립터 : __get__, __set__, __delete__
클래스 서비스 : __prepare__, __instancecheck__, __subclasscheck__
※ 출처 : 전문가를 위한 파이썬
'공부하는삶 > Python' 카테고리의 다른 글
Python (Avoiding) Flow Control (0) | 2023.08.29 |
---|---|
Python Composite pattern(composition), Descriptor, Meta class (0) | 2023.08.29 |
Sequence (0) | 2020.05.09 |
Gaussian Filter vs Bilateral Filter (0) | 2020.04.02 |
Python Multiprocessing module(파이썬 멀티프로세싱 모듈) (0) | 2019.11.28 |
Tensorflow 시작하기 - 1 (0) | 2019.11.28 |