Programming Languages/Python

특수 메서드 (매직 메서드)

newclass 2025. 3. 26. 04:08

특수 메서드 (매직 메서드)

1. 특수 메서드란?

파이썬의 특수 메서드(매직 메서드)는 이중 밑줄(__)로 시작하고 끝나는 메서드로, 특정 동작이나 연산자의 동작을 정의합니다. 이를 통해 객체의 행동을 사용자 정의할 수 있습니다.

2. 주요 특수 메서드

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    # 문자열 표현
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __str__(self):
        return f"({self.x}, {self.y})"
    
    # 벡터 덧셈
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    # 벡터 뺄셈
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)
    
    # 벡터 길이
    def __len__(self):
        import math
        return int(math.sqrt(self.x**2 + self.y**2))
    
    # 항목 접근
    def __getitem__(self, key):
        if key == 0:
            return self.x
        elif key == 1:
            return self.y
        else:
            raise IndexError("Vector 인덱스는 0 또는 1이어야 합니다.")
    
    # 비교 연산자
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    
    # 불리언 문맥에서의 평가
    def __bool__(self):
        return bool(self.x or self.y)

# 특수 메서드 활용
v1 = Vector(3, 4)
v2 = Vector(5, 6)

print(v1)                # __str__ 호출: (3, 4)
print(repr(v1))          # __repr__ 호출: Vector(3, 4)
print(v1 + v2)           # __add__ 호출: (8, 10)
print(v1 - v2)           # __sub__ 호출: (-2, -2)
print(len(v1))           # __len__ 호출: 5
print(v1[0], v1[1])      # __getitem__ 호출: 3 4
print(v1 == Vector(3, 4))  # __eq__ 호출: True
print(bool(v1))          # __bool__ 호출: True
print(bool(Vector(0, 0)))  # __bool__ 호출: False