PYTHON - 파이썬 데이터 모델 (Special Method)

Python Data Model (데이터 모델)

파이썬은 객체 지향 언어이다. (Object-Oriented-Programming; OOP) 따라서 파이썬의 모든 데이터는 객체(object)로 저장된다. 또한 모든 객체는 메모리의 주소값(id), 자료형(type), 그리고 값(value)를 갖는다.

Special Method (특별 메소드)

definition

special method가 구현된 클래스의 객체는 내장 함수(built-in function)를 사용할 수 있다.
파이썬의 모든 내장 자료형(built-in data type)역시 데이터를 연산 및 처리할 수 있는 special method가 구현되어 사용자가 편리하게 내장 연산자 및 함수를 사용할 수 있다.
예를 들어, list를 인덱싱하고 싶을 때, 인덱싱 연산자인 list[index]로 인덱싱 할 수 있는 이유는 list 자료형에 __getitem__ special method가 구현됐기 때문이다.
special method는 항상 함수명 시작과 끝에 __ (double underscores)를 넣어준다.

x = [1,2,3]
x[0] # 1
x.__getitem__(0) # 1

파이썬 인터프리터가 이미 작동 방식을 알고 있는 연산, 함수, 또는 자료형을 내장 (built-in) 연산, 함수, 또는 자료형이라고 한다.
만약 내가 새로운 클래스를 정의하고 싶을 때, special method를 사용하면 내가 만든 클래스가 built-in datatype이 될 수 있고, 내장 함수를 사용할 수 있다.

types
  • 객체 생성 및 소멸
    • __init__
    • __del__
  • 객체를 문자열로 반환
    • __str__
      • 사용자가 객체에 내장 함수 str(), print()를 사용 가능.
    • __repr__
      • 사용자가 객체에 내장 함수 repr()를 사용 가능.

만약 클래스에 __str__ special method를 구현하지 않았다면 instance의 정보가 출력된다.

class MyName:
	def __init__(self, name):
		self.name = name

sjshin=MyName("sjshin")
print(sjshin)
# <__main__.MyName object at 0x7f2f1098f410>
str(sjshin)
# '<__main__.MyName object at 0x7f2f1098f410>'

클래스에 __str__ special method를 구현하면 내장 함수 str(), print()로 값을 출력할 수 있다.

class MyNameStr:
	def __init__(self, name):
		self.name = name
	def __str__(self):
		return f"{self.name}"

sjshin=MyNameStr("sjshin")
print(sjshin)
# sjshin
str(sjshin)
# sjshin
  • 반복
    • __iter__
    • __next__
    • __reversed__
  • collection emulation
    • __getitem__
    • __len__
    • __contains__
    • __setitem__
  • callable emulation
    • __call__
  • 속성 관리
    • __getattr__
    • __setattr__
    • __delattr__
    • __dir__
usage
  • special method는 유저가 아니라 파이썬 인터프리터가 실행하는 메소드다.
  • 사용자가 내장 함수에 특정한 객체를 입력했을 때 (ex. len(obj)) 파이썬 인터프리터는 객체의 special method(ex. ojb.__len__())를 호출한다.
  • special method는 사용자가 내장 함수를 사용할 수 있게한다. 따라서 사용자는 객체 사용이 한층 편리해진다.

Reference

str, repr
types and objects in python