Repository navigation
Expand file tree
/
Copy pathmagicMethod.py
More file actions
64 lines (45 loc) · 1.92 KB
/
Copy pathmagicMethod.py
File metadata and controls
64 lines (45 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 매직 메서드 : 이름 앞뒤에 __ 가 붙은 특별한 메서드
# 파이썬이 특정 상황에서 자동으로 불러 준다
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(p) # <__main__.Point object at 0x...> — 읽을 수 없다
class Point2:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self): # print() 할 때 불린다
return f'({self.x}, {self.y})'
def __repr__(self): # 개발자용 표현. 리스트 안에 있을 때 등
return f'Point2(x={self.x}, y={self.y})'
def __eq__(self, other): # == 비교
return self.x == other.x and self.y == other.y
def __add__(self, other): # + 연산
return Point2(self.x + other.x, self.y + other.y)
a = Point2(3, 4)
b = Point2(1, 2)
print(a) # (3, 4) ← __str__
print([a, b]) # [Point2(...)] ← __repr__
print(a == Point2(3, 4)) # True ← __eq__
print(a + b) # (4, 6) ← __add__
class Basket:
def __init__(self, items):
self.items = items
def __len__(self): # len() 할 때
return len(self.items)
def __getitem__(self, idx): # [] 로 꺼낼 때
return self.items[idx]
def __contains__(self, x): # in 검사할 때
return x in self.items
bk = Basket(['사과', '바나나', '딸기'])
print(len(bk)) # 3
print(bk[1]) # 바나나
print('딸기' in bk) # True
for item in bk: # __getitem__ 이 있으면 for 도 된다
print(item, end=' ')
print()
print('---------- 이미 써 왔습니다 ----------')
# len(리스트), 문자열 + 문자열, 3 in [1,2,3] 전부 매직 메서드입니다.
# 내장 자료형이 하던 일을 내 클래스도 할 수 있게 만드는 장치입니다.