Python에서는 매직 메서드(magic methods)를 사용하여 연산자의 오버로드 동작을 직접 정의할 수 있습니다. 비교 연산자(<, <=, >, >=, ==, !=)를 오버로드하려면 각각에 대응되는 매직 메서드인 __lt__, __le__, __gt__, __ge__, __eq__, __ne__에 원하는 동작을 정의하면 됩니다.
비교 연산자와 매직 메서드의 매핑
<(미만) →__lt__<=(이하) →__le__>(초과) →__gt__>=(이상) →__ge__==(같음) →__eq__!=(같지 않음) →__ne__
예제 코드
아래 프로그램은 distance 클래스의 객체끼리 비교할 수 있도록 == 연산자와 >= 연산자를 오버로드한 예시입니다.
class distance:
def __init__(self, x=5, y=5):
self.ft = x
self.inch = y
def __eq__(self, other):
if self.ft == other.ft and self.inch == other.inch:
return "both objects are equal"
else:
return "both objects are not equal"
def __ge__(self, other):
in1 = self.ft * 12 + self.inch
in2 = other.ft * 12 + other.inch
if in1 >= in2:
return "first object greater than or equal to other"
else:
return "first object smaller than other"
d1 = distance(5, 5)
d2 = distance()
print(d1 == d2)
d3 = distance()
d4 = distance(6, 10)
print(d1 == d2)
d5 = distance(3, 11)
d6 = distance()
print(d5 >= d6)
실행 결과
위 프로그램을 실행하면 오버로드된 == 연산자와 >= 연산자가 적용된 결과를 확인할 수 있습니다.
both objects are equal
both objects are equal
first object smaller than other
코드 설명
distance 클래스는 피트(ft)와 인치(inch) 단위의 길이를 나타냅니다. 기본 생성자에서 피트와 인치 값은 각각 5로 초기화됩니다.
__eq__메서드: 두 객체의 피트 값과 인치 값이 모두 같으면 두 객체가 동등하다고 판단합니다.__ge__메서드: 피트 값을 인치로 변환(피트 × 12 + 인치)하여 전체 길이를 계산한 뒤, 첫 번째 객체가 두 번째 객체보다 크거나 같은지 비교합니다.
예제에서 d5(3피트 11인치)는 d6(5피트 5인치)보다 전체 길이가 작기 때문에 "first object smaller than other"라는 결과가 출력됩니다.