스페셜 메서드
: 파이썬의 스페셜 메서드(또는 매직 메서드라고도 불림)는 더블 언더스코어(__)로 시작하고 끝나는 메서드 이름을 갖는다.
이 메서드들은 특정 구문이나 내장 함수를 사용할 때 파이썬 인터프리터에 의해 자동으로 호출된다.
class Book:
def __init__(self, title):
self.title = title
book = Book('미친듯이 재밌는 파이썬')
print(book)
print(str(book))
<__main__.Book object at 0x7f9c19c83910>
<__main__.Book object at 0x7f9c19c83910>
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return self.title
book = Book('미친듯이 재밌는 파이썬')
print(book)
print(str(book))
미친듯이 재밌는 파이썬
미친듯이 재밌는 파이썬
li = [1, 2, 3, 4, 5]
print(li)
print(str(li))
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
class Calc:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other.value
num1 = Calc(5)
num2 = Calc(10)
result = num1 + num2
print(result)
15
class Queue:
def __init__(self):
self.items = [1, 2, 3, 4, 5]
def __len__(self):
return len(self.items)
queue = Queue()
print(queue)
print(len(queue))
<__main__.Queue object at 0x7f9c19c83c70>
5
li = [1,2,3,4,5]
print(len(li))
5
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __getitem__(self, index):
if index == 0:
return self.x
elif index == 1:
return self.y
else:
return -1
pt = Point(5, 3)
print(pt[0])
print(pt[1])
print(pt[10])
5
3
-1
class CallableObject:
def __call__(self, *args, **kwargs):
print(f'{args}, {kwargs}')
callableObj = CallableObject()
callableObj(10, 20, 30, 40, 50, userid='apple', age=20, gender='여자')
(10, 20, 30, 40, 50), {'userId': 'apple', 'age': 20, 'gender': '여자'}
'코딩 > 파이썬' 카테고리의 다른 글
파이썬 과제 (4). 주민등록번호 유효성 검사 (0) | 2024.03.20 |
---|---|
파이썬의 예외처리 (0) | 2024.03.20 |
파이썬 상속 (0) | 2024.03.19 |
객체지향과 클래스2 (0) | 2024.03.19 |
파이썬 과제 (3). 로또 예측 프로그램 (0) | 2024.03.19 |