sklass의 s-class 프로그래밍 blog

namedtuple 사용법 본문

python

namedtuple 사용법

sklass 2021. 8. 23. 00:10

파이썬의 자료형 중에 namedtuple이라는 자료형이 있습니다. namedtuple은 int나 str같이 Class형태가 아닌 collections라는 파이썬 내장 모듈안에 정의되어 있습니다. Collections에 있는 자료형은 아래와 같습니다.

  • namedtuple
  • deque
  • Chainmap
  • Counter
  • OrderedDict
  • defaultdict
  • UserDict
  • UserList
  • UserString

이번 포스트는 colletions 모듈안에 namedtuple이라는 자료형에 대해서 알아보겠습니다.

 

본래 tuple은, 항목에 인덱스(index)로 접근하므로 직관적이지 않습니다. 예를들어, mytuple[0], mytuple[1]과 같이 0번째와 1번째 항목에 대한 정보를 구체적으로 알기 힘듭니다.

 

하지만, namedtuple은 mynametuple.age, mynamedtuple.birth와 같이 dict 형태로 접근 가능하여 가독성이 높고, 각 항목에 대한 보다 구체적인 정보를 알 수 있습니다. 또한, 본래 tuple과 마찬가지로 인덱스로 데이터 접근도 가능합니다.

 

예제 코드를 살펴보겠습니다.

from collections import namedtuple

Person = namedtuple("Person", "name, age, phone_num")
person_john = Person("John", 26, "010-3333-3333")

print(person_john.name)
>> 'John'

print(person_john.age)
>> 26

print(person_john[2])
>> '010-3333-3333'

'python' 카테고리의 다른 글

Celery  (0) 2021.09.01
__(double underscore)  (0) 2021.08.27
@property  (0) 2021.08.26
py_src 파일 구조  (0) 2021.08.26
Python Decorator  (0) 2021.08.24