1. 매직 메소드
매직 메소드는 더블 언더스코어로 시작하고 끝나는 특별한 메소드이다.
파이썬의 내장 동작과 관련이 있고, 특별한 연산을 수행하는 방법을 제공한다.
1.1 객체 초기화와 소멸
1.1.1 __init__(self, ...) (초기화 메소드)
메소드는 클래스의 인스턴스가 생성될 때 자동으로 호출되어 객체를 초기화한다.
class MyClass:
def __init__(self, value):
self.value = value
obj = MyClass(10)
print(obj.value) # 출력: 10
1.1.2 __del__(self) (소멸자 메소드)
객체가 삭제되거나 메모리에서 해제될 때 호출한다.
class MyClass:
def __init__(self, value):
self.value = value
def __del__(self):
print(f"{self.value} 객체가 삭제되었습니다.")
obj = MyClass(10)
del obj # 출력: 10 객체가 삭제되었습니다.
1.2 연산자 오버로딩
1.2.1 산술 연산자
- __add__(self, other) - + 연산자
- __sub__(self, other) - `` 연산자
- __mul__(self, other) - `` 연산자
- __truediv__(self, other) - / 연산자
- __floordiv__(self, other) - // 연산자
- __mod__(self, other) - % 연산자
- __pow__(self, other) - * 연산자
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2) # 출력: Vector(6, 8)
1.2.2 비교 연산자
- __eq__(self, other) - == 연산자
- __ne__(self, other) - != 연산자
- __lt__(self, other) - < 연산자
- __le__(self, other) - <= 연산자
- __gt__(self, other) - > 연산자
- __ge__(self, other) - >= 연산자
class Vector:
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
v1 = Vector(2, 3)
v2 = Vector(2, 3)
v3 = Vector(4, 5)
print(v1 == v2) # 출력: True
print(v1 == v3) # 출력: False
1.3 리스트, 튜플, 딕셔너리 관련 메소드
1.3.1 __len__(self)
객체의 길이를 반환
class MyList:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
my_list = MyList([1, 2, 3])
print(len(my_list)) # 출력: 3
1.3.2 __getitem__(self, key)
인덱스를 통해서 값을 가져올 때 호출된다.
class MyList:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
my_list = MyList([1, 2, 3])
print(my_list[0]) # 출력: 1
1.3.3 __setitem__(self, key, value)
인덱스를 통해서 값을 설정할 때 호출
class MyList:
def __init__(self, data):
self.data = data
def __setitem__(self, index, value):
self.data[index] = value
my_list = MyList([1, 2, 3])
my_list[0] = 10
print(my_list[0]) # 출력: 10
1.3.4 __delitem__(self, key)
인덱스를 통해서 값을 삭제할 때 호출
class MyList:
def __init__(self, data):
self.data = data
def __delitem__(self, index):
del self.data[index]
my_list = MyList([1, 2, 3])
del my_list[0]
print(my_list.data) # 출력: [2, 3]
1.4 문자열 표현 관련 매직 메소드
1.4.1 __str__(self)
사용자 문자열 표현을 반환
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyClass with value: {self.value}"
obj = MyClass(10)
print(obj) # 출력: MyClass with value: 10
1.4.2 __repr__(self)
객체의 공식적 문자열 표현을 반환한다.
class MyClass:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"MyClass({self.value})"
obj = MyClass(10)
print(repr(obj)) # 출력: MyClass(10)
'Language > Python' 카테고리의 다른 글
[Python] 이터레이터, 제너레이터, 데코레이터 (0) | 2024.04.28 |
---|---|
[Python] 클래스 (2/2) (0) | 2024.04.28 |
[Python] 클래스 (1/2) (0) | 2024.04.27 |
[Python] 패키지 설치 및 관리 (0) | 2024.04.27 |
[Python] 모듈과 패키지 (0) | 2024.04.27 |