본문 바로가기
개발/Python

🪄매직 메소드 __xxx__

by shining park 2025. 4. 17.

Product 클래스의 객체를 출력하려고 하지만 __str__()이 정의되어 있지 않아서 출력 결과가 Product object at 0x... 형태로 나옴

Python의 매직 메소드 __str__() 메소드를 추가하여 해결

 

🪄매직 메소드 = 더블 언더 메소드 = (줄여서) 던더 메소드🪄

 

__str__() 메서드란?

    • __str__()는 객체를 print() 하거나 문자열로 변환할 때 (str(obj)) 자동으로 호출되는 문자열 표현 메서드
    • print(p) 했을 때 자동으로 __str__() 결과가 출력
    • 없으면 객체가 <__main__.Product object at 0x000...> 같은 이상한 형으로 출력
class Product:
	# 객체가 생성될 때 호출되는 생성자
    def __init__(self, name, price):
        self.__name = name
        self.__price = price

	# 객체가 문자열로 출력될 때 호출 (print, str())
    def __str__(self):
        return f'{self.__name} - {self.__price}원'

p = Product('아이폰', 1500000)
print(p)  # 아이폰 - 1500000원

 

알아두면 좋은 다른 매직 메서드들

메서드 설명
__init__(self, ...) 생성자, 객체가 생성될 때 호출됨
__str__(self) 객체를 문자열로 표현할 때 호출됨 (print(obj))
__repr__(self) 개발용 문자열 표현 (디버깅 시 사용)
__len__(self) len(obj) 호출 시 사용
__eq__(self, other) obj1 == obj2 비교 시 호출
__lt__(self, other) < 비교 시
__getitem__(self, key) obj[key] 접근 시
__setitem__(self, key, value) obj[key] = value 할당 시
__del__(self) 객체가 소멸될 때 호출됨 (거의 안 씀)

 

예시

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f'상품: {self.name}, 가격: {self.price}원'

    def __eq__(self, other):
        return self.name == other.name and self.price == other.price

p1 = Product('에어팟', 250000)
p2 = Product('에어팟', 250000)

print(p1)             # 상품: 에어팟, 가격: 250000원
print(p1 == p2)       # True (내용이 같으면 같다고 판단함)

'개발 > Python' 카테고리의 다른 글

Scikit-Learn > fit(), transform()  (0) 2025.05.10
DB > fetchmany, fetchone, fetchall  (0) 2025.04.27
🦭바다코끼리 연산자  (0) 2025.04.13
string to boolean 형변환  (1) 2025.04.09
시간대(Timezone) 처리 방식  (0) 2025.04.09