클래스 안에 정의된 함수를 우리는 특별히 '메소드(method)'라고 한다. 메서드 중에서 __
로 시작해서 __
로 끝나는 메소드들이 있는데 이를 매직 메소드 또는 특별 메소드(special method)라고 부릅니다.
이외에도 매직 메소드의 종류는 매우 많다. 공식문서에서 확인할 수 있다.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return str(self.name)
def __eq__(self, other):
return (self.name == other.age) and (self.age == other.age)
def __add__(self, other):
return self.age + other.age
student1 = Student('짱구', 5)
student2 = Student('철수', 5)
print(student1) # 짱구
print(student1==student2) # False
print(student1+student2) # 10