1. 파이썬 데이터 모델

 

Remarks

이 글은 전문가를 위한 파이썬(Fluent Python)을 정리한 자료입니다.


1. 파이썬 데이터 모델

  • 파이썬의 최고 장점 중 하나는 일관성이다.

데이터 모델 (파이썬 객체 모델)
시퀀스, 반복자, 함수, 클래스, 콘텍스트 관리자 등 언어 자체의 구성단위에 대한 인터페이스를 공식적으로 정의하는 일종의 프레임워크

특별 메서드 (magic method, dunder method)
기본적인 객체 연산을 수행하기 위해 인터프리터가 호출하는 메서드
__getitem()__과 같이 앞뒤에 이중 언더바(dunder-getitem)를 가진다.

1.1 파이썬 카드 한 벌

  • 객체에 대하여 in 연산을 수행할 때, __contains__() 를 가지고 있지 않다면 __getitem__() 을 이용하여 brute force search 수행
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Deck:
  def __init__(self):
    self._cards = [1, 2, 3, 4, 5]
  
  def __len__(self):  # len()
    return len(self._cards)
  
  def __getitem__(self, pos):  # []
    return self._cards[pos]

  def __contains__(self, e):  # in
    return binarysearch(self._cards, e)  # return should be bool

deck = Deck()
1
2
3
4
5
6
7
8
9
10
11
12
# deck.__len__()
len(deck)  

# deck.__getitem__(0)
deck[0]    

# deck.__iter__() -> __getitem__()
for card in deck:
  print(card)

from random import choice
choice(deck)

1.2 특별 메서드는 어떻게 사용되나?

  1. 사용자 정의 속성을 만들 때 dunder 형태의 속성명은 피하라

1.2.1 수치형 흉내 내기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from math import hypot

class Vector:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  
  def __repr__(self):  # str() -> repr()
    return f'Vector({self.x:r}, {self.y:r})'
  
  def __abs__(self):  # abs()
    return hypot(self.x, self.y)  # hypot(x, y): \sqrt(x**2 + y**2)
  
  def __bool__(self):  # bool()
    return bool(abs(self))
    
  def __add__(self, other):  # +
    x = self.x + other.x
    y = self.y + other.y
    return Vector(x, y)
  
  def __mul__(self, scalar):  # *
    return Vector(scalar * self.x, scalar * self.y)
  • Python interpreter는 __str__()가 구현되어 있지 않을 때, __repr__()를 호출한다.
  • 연산자에 대한 특별 메서드명

    범주 메서드명 및 관련 연산자
    콘텍스트 관리 __enter__
    __exit__
    향상된 비교 연산자 __lt__: <
    __eq__: =
    __gt__: >
    산술 연산자 __add__: +
    __sub__: -
    __mul__: *
    __truediv__: /
    __floordiv__: //
    __mod__: %
    __pow__: **
    __round__: round()

1.5 요약

  • 특별 메서드를 구현하면 사용자 정의 객체도 내장형 객체처럼 작동하게 되어, 파이썬스러운(pythonic) 표현력 있는 코딩 스타일을 구사할 수 있다.