Python Study

CH1. 특별메서드

Louis.T.Kim 2020. 7. 21. 14:08

200721

제목 1

1. 특별 메서드

(예시)

__len()__ : 길이를 return

__getitem()__ : obj[key] 형태의 호출을 지원

hello

Class FrenchDeck:
  def __getitem__(self, position):
     return self._cards[position]

위에서 처럼 __getitem__의 return이 List로 재정의 된 경우, Object를 상속받았음에도 불구하고 instance는 표준 파이썬 List처럼 행동한다. 따라서 reversed(), choice(), sorted() 등을 사용할 수 있게 된다. 아래 4가지 예시를 보자

deck = FrenchDeck()

# EX 1 : Random Choice
from random import choice
choice(deck)

# EX 2 : Act as a List
deck[:3]

# EX 3 : Iterable & Reversable
for card in reversed(deck):
    print(card)


# EX 4 : Advanced Sort
# Part 1 : Comparator
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
def spades_high(card):
    rank_value = FrenchDeck.ranks.index(card.rank)
    return rank_value * len(suit_values) + suit_values[card.suit] # number, shape 순으로 높은 Score

# Part 2 : Sort
for card in sorted(deck, key=spades_high):
    print(card)


위와 같이 특별 메서드를 customize 하지 않는 경우, list, str, bytearray 등 파이썬의 내장 자료형에서는 len(), obj[pos] 등이 호출 될 때, 파이썬 인터프리터는 CPython의 경우 C struct를 직접 찾아서 값을 반환한다.