Python(파이썬): 매직 메소드

매직 메소드란 간단히 말하면 클래스 안에 정의할 수 있는 특별한 빌트인 메소드입니다. dunder 메서드(이중 밑줄 메서드)라고도 알려진 매직 메서드는 __init__, __str__, __len__ 등과 같이 이중 밑줄로 둘러싸인 이름으로 표시되는 Python의 특수 메서드입니다. 간단하게 매직 메서드를 이용하여, 데이터를 처리하는 예를 가져왔습니다.

제목, 저자, 출판 연도와 같은 속성을 가진 책을 나타내는 클래스를 생성한다고 가정해 보겠습니다. 문자열 표현, 길이, 비교와 같은 동작을 정의하기 위해 매직 메서드를 사용할 수 있습니다.

class Book:
    def __init__(self, title, author, year):
        self.title = title
        self.author = author
        self.year = year

    def __str__(self):
        return f"{self.title} by {self.author} ({self.year})"

    def __len__(self):
        # 책 제목의 길이를 정의
        return len(self.title)

    def __eq__(self, other):
        # isinstance로 비교하는 인스턴스가 Book 클래스로 만들어진 인스턴스인지 확인
        if isinstance(other, Book):
            # title, author, and year를 보고 동일한 인스턴스인지 검사
            return (self.title, self.author, self.year) == (other.title, other.author, other.year)
        return False

    def __lt__(self, other):
        # 출판년도가 빠른지 비교
        if isinstance(other, Book):
            return self.year < other.year
        return NotImplemented

# Book class로 인스턴스 생성
book1 = Book("Python for Beginners", "John Smith", 2020)
book2 = Book("Advanced Python Techniques", "Jane Doe", 2022)
book3 = Book("Python for Beginners", "John Smith", 2020)

# 인스턴스 출력 시, __str__ 메소드에서 반환 값 출력
print(book1)  # Output: Python for Beginners by John Smith (2020)

# len(인스턴스) 실행 시, __len__ 메소드에서 반환 값 출력
print(len(book1))  # Output: 20

# == 연산 시, __eq__ 메소드에서 반환 값 출력
print(book1 == book2)  # Output: False
print(book1 == book3)  # Output: True

# < 비교 연산 시, __lt__ 메소드에서 반환 값 출력
print(book1 < book2)  # Output: True (2020 < 2022)

Leave a Comment