Guidelines
Practice
Guidelines

클래스의 특수 메소드

클래스의 특수 메소드는 객체의 동작을 정의하고, 파이썬의 내장 함수와의 상호작용을 관리합니다.

이러한 메소드들은 '매직 메소드(Magic method)'라고도 불리며, 더블 언더스코어(__, 밑줄 2개)로 시작하고 끝납니다.


특수 메소드 사용 예시

__str__, __eq__ 특수 메소드 예시
class Book: def __init__(self, title, author): self.title = title self.author = author def __str__(self): return f"{self.title} by {self.author}" def __eq__(self, other): return self.title == other.title and self.author == other.author # 클래스 사용 예시 book1 = Book("해리포터", "J.K. 롤링") print(book1) # '해리포터 by J.K. 롤링' 출력 book2 = Book("해리포터", "J.K. 롤링") book3 = Book("지구 끝의 서점", "페넬로페") print(book1 == book2) # title과 author가 모두 같으므로 True print(book1 == book3) # False

이 예제에서 __str__ 메소드는 Book 객체를 문자열로 나타내고, __eq__ 메소드는 두 Book 객체가 같은 책인지 비교합니다.


특수 메소드 종류

  • __str__(self): 객체를 문자열로 표현할 때 사용됩니다. print() 함수나 str() 함수가 호출될 때 실행됩니다.

  • __eq__(self, other): == 연산자를 재정의하여 객체 간의 동등성 비교를 정의합니다.

  • __ne__(self, other): != 연산자를 재정의하여 객체 간의 부등성 비교를 정의합니다.

  • __gt__(self, other): > 연산자를 재정의하여 객체 간의 크기 비교를 정의합니다.

  • __ge__(self, other): >= 연산자를 재정의하여 객체 간의 크기 비교를 정의합니다.

  • __lt__(self, other): < 연산자를 재정의하여 객체 간의 크기 비교를 정의합니다.

  • __le__(self, other): <= 연산자를 재정의하여 객체 간의 크기 비교를 정의합니다.

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help