던더 메서드
Python에는 밑줄 두 개로 감싼 특별한 메서드 이름들이 있고, 소리 내어 던더(dunder) 메서드라고 불러요. __init__은 이미 만났어요. 다른 것들은 객체가 출력, 같음 비교, 정렬 같은 내장 연산과 자연스럽게 어울리게 해 줘요.
출력: __str__과 __repr__
__str__은 print()와 str()이 보여 주는 것을 정해요. __repr__은 개발자용 버전으로, 대화형 셸과 리스트 안에서 쓰여요. 적어도 하나는 정의하는 게 좋은 습관이에요.
class Money:
def __init__(self, cents):
self.cents = cents
def __str__(self):
return f"${self.cents / 100:.2f}"
def __repr__(self):
return f"Money({self.cents})"
m = Money(150)
print(m) # $1.50
print(repr(m)) # Money(150)같음: __eq__
기본적으로 두 객체는 말 그대로 같은 객체일 때만 같아요. __eq__(self, other)는 대신 값으로 비교하게 해 줘요.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Point(1, 2) == Point(1, 2)) # True__eq__에는 함정이 하나 따라와요: 그것을 정의하는 순간 Python이 __hash__를 None으로 정해서, 객체가 해시 불가능해져요. 그런 다음 그것을 set에 넣거나 dict 키로 쓰면 TypeError: unhashable type: 'Point'가 나요. 이유는 Python이 기대는 규칙, 같은 객체는 같은 해시를 가져야 한다는 규칙 때문이라서, 같음을 다시 정의하면 일부러 다시 선택하게 만들어요. 그게 필요하면 비교하는 것과 같은 필드로 만든 __hash__를 더하거나, 둘 다 써 주는 frozen dataclass(@dataclass 레슨에서 다뤄요)를 쓰세요.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y)) # same fields as __eq__
print(len({Point(1, 2), Point(1, 2)})) # 1, and no TypeError순서: __lt__
__lt__(self, other)는 작다(less-than) 규칙을 정의하고, 그것만으로 sorted()가 객체를 정렬할 수 있어요.
class Score:
def __init__(self, points):
self.points = points
def __lt__(self, other):
return self.points < other.points
def __repr__(self):
return f"Score({self.points})"
print(sorted([Score(3), Score(1), Score(2)]))
# [Score(1), Score(2), Score(3)]__init__에서 self.degrees를 저장하는 클래스 Temp를 정의하세요. "20C"처럼(숫자 뒤에 C) 문자열을 돌려주는 __str__, 도수가 같으면 두 온도가 같도록 하는 __eq__, 그리고 온도 리스트를 정렬할 수 있게 degrees로 비교하는 __lt__를 더하세요.
이 연습은 곧 열려요
앞의 레슨을 마치면 이 레슨이 열려요. 강좌 전체가 무료이고 계정도 필요 없으며, 이 레슨은 지금 바로 읽을 수 있어요.
이 브라우저가 learn.floati.life의 쿠키를 막고 있어서, 여기서 마친 레슨들이 순서대로 열리지 않아요. 이 사이트의 쿠키를 허용하고 새로고침하세요.