파이썬/파이썬(python) 중급

[18-5 파이썬] 네임튜플 namedtuple

Olivia-BlackCherry 2022. 8. 27. 09:49
네임튜플 namedtuple 사용하는 이유

코드의 가독성이 좋아진다.

튜플 값이 어떤 내용인지 이름을 통해 알 수 있기 때문에 코드가 명확해진다.

메모리 사용도 효율적이다.

 

딕셔너리의 key, value에서, key와 같은 역할이라고 봐도 무방하다.

하지만 딕셔너리보다 더 단순하고, 작성하기도 빠르다.

 

지금부터 네임튜플을 공부해보자.

클래스, 객체 개념으로 접근해보겠다.

 

네임튜플 nametuple 만드는 방법

1. collections에서 namedtuple을 import하기

from collections import namedtuple

 

2. 네임튜플(namedtuple) 만들기

class_name = Student

field = ["kindness", "friends", "MBTI"]

 

[코드]

#Student 클래스 만들기(이름: kindness, friends, MBTI)
Student = namedtuple('Student', ['kindness', 'friends', 'MBTI'])
print(Student)

[실행 화면]

 

3. 객체 만들기

[코드]

#Student 클래스의 olivia 객체 만들기
tony = Student(kindness = 10, friends = 5, MBTI = "ENFP")
print(tony)

jenny = Student(8, 3, "INFJ")
print(jenny)

[실행화면]

 

4. 접근하기

[코드]

print(jenny.kindness)
print(jenny[0])

[실행화면]

 

[전체코드]

from collections import namedtuple

#Student 클래스 만들기(이름: kindness, friends, MBTI)
Student = namedtuple('Student', ['kindness', 'friends', 'MBTI'])
print(Student)

#Student 클래스의 olivia 객체 만들기
tony = Student(kindness = 10, friends = 5, MBTI = "ENFP")
print(tony)

jenny = Student(8, 3, "INFJ")
print(jenny)

print(jenny.kindness)
print(jenny[0])