티스토리 뷰

Python

17. 파이썬의 스페셜 메서드

muru_ 2024. 3. 19. 17:21

1. 스페셜 메서드 (매직 메서드)

- 더블 언더스코어(__)로 시작하고 끝나는 메서드 이름을 가짐
- 특정 구문이나 내장 함수를 사용할 때 파이썬 인터프리터에 의해 자동으로 호출

- 예를 들어, 객체에 대해 + 연산자를 사용하면 해당 객체의 add 메서드가 호출
- len() 함수를 사용하면 len 메서드가 호출됩니다.

 

1) __init__ : 객체 초기화 메서드

2) __str__ : 객체를 문자열로 표현하는 메서드. print() 함수나 str() 함수를 사용할  호출.

class Book:
  def __init__(self, title):
    self.title = title

book = Book('미친듯이 재밌는 파이썬')
print(book)
print(str(book))    # 객체의 특성을 찍어주는 것이 원래 기능

class Book:
  def __init__(self, title):
    self.title = title
  def __str__(self):        # object 클래스에서 내려온 것을 오버라이딩 시키는 것
    return self.title
    
book = Book('파이썬')
print(book)            # '파이썬' 출력
print(str(book))       # '파이썬' 출력
li = [1, 2, 3, 4, 5]
print(li)
print(str(li))    # 리스트를 개발할 때 str을 쓰면 그 안에 속성값이 나오도록 코딩해놓은 것

 

 

3) __add__ : + 연산자를 사용할  호출되는 메서드

class Calc:
  def __init__(self, value):
    self.value = value
  def __add__(self, other):
    return self.value + other.value
    
num1 = Calc(5)
result = num1 + 10      # num1은 객체의 밸류
print(result)           # 오류
# AttributeError: 'int' object has no attribute 'value'

num1 = Calc(5)
num2 = Calc(10)
result = num1 + num2      # Calc 라는 객체에 한해서 + 가 오버라이딩 됨
print(result)

 

 

4) __len__ : len() 함수를 사용할  호출되는 메서드

class Queue:
  def __init__(self):
    self.items = [1, 2, 3, 4, 5]

queue = Queue()
print(queue)
print(len(queue))     # 에러, 순차적으로 데이터가 들어가있는 자료구조가 아님
# TypeError: object of type 'Queue' has no len()

class Queue:
  def __init__(self):
      self.items = [1, 2, 3, 4, 5]

  def __len__(self):         # len을 오버리이딩
      return len(self.items)
      
queue = Queue()
print(queue)
print(len(queue))    # 5

 

 

5) __getitem__ : 인덱싱을 사용할  호출되는 메서드

class Point:
  def __init__(self, x, y):
    self.x = x
    self.y = y

  def __getitem__(self, index):    # list에서 값 뽑는 방식을 오버라이딩
    if index == 0:
      return self.x
    elif index == 1:
      return self.y
    else:
      return -1

pt = Point(5, 3)
print(pt[0])       # 5, 0이 getitem 의 index에 들어가게 됨
print(pt[1])       # 3
print(pt[2])       # -1

 

 

6) __call__ : 객체를 함수처럼 호출할  사용되는 메서드

class CallableObject:
  def __call__(self, *args, **kwargs):    # argument : 매개변수, keywordargument : 키 = 밸류
    print(f'{args}, {kwargs}')            # * : 튜플로 받음
                                          # ** : 키와 밸류로 받음 (딕셔너리)

cobj = CallableObject()
cobj(10, 20, 30, 40, 50, userid='apple', age=20, gender='남자' ) 
# 앞에는 튜플, 뒤에는 딕셔너리
# 결과 : (10, 20, 30, 40, 50), {'userid': 'apple', 'age': 20, 'gender': '남자'}

 

 

 

 

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
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
글 보관함