매직(special) 메소드

이상우·2022년 6월 15일
0

매직 메소드

클래스안에 정의할 수 있는 특별한(Built-in)<-이미 파이썬에서 만들어져있는 메소드
예를 들면 __init__ 을 가장 흔하게 봤을 것이다.
__init__ 은 클래스를 생성하기 위한 인스턴스 변수를 정의할때 쓰는 메소드이다. 좀 더 정확하게 설명하기 위해서는 __add__ 라는 메소드는 add이름 그대로 더하는 메소드이다. 그전까지 흔하게 썼던 +도 사실 기존에 python에서 정의되어있는 __add__ 메소드 덕분에 아래처럼 더하기를 쓸 수 있었던 것이다.

add_num = 3 + 2
add_num # 5가 출력

그 외에 add 뿐만 아니라 다양한 메소드가 있는데 그것은 아래 사이트 공식문서를 보면 여러가지 매직 메소드를 볼 수 있다.
매직 메소드 python 공식문서

네임드 튜플

정의

namedtuple() Factory Function for Tuples with Named Fields. Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index. namedTuple python 공식문서

from collections import namedtuple

# 네임드 튜플 선언
Point = nametuple('Point', 'x y')

pt1 = Point(1.0, 5.0)
print(pt1) # Default Point(x=1.0, y=5.0)

# 네임드 튜플 선언 방법
Point1 = namedTuple('Point', ['x', 'y'])
Point2 = namedTuple('Point', 'x, y')
Point3 = namedTuple('Point', 'x y')
Point4 = namedTuple('Point', 'x y x class', rename=True) # Default = False

# 객체 생성 방법
p1 = Point1(x=10, y=35)
p2 = Point2(20, 40)
p3 = Point3(45, y=35)
p4 = Point4(10, 20, 30, 40) # 변수 개수가 안맞으면 에러발생

네임드 튜플을 사용하면 위와 같이 명시적으로 보기 좋으며, 키 값 혹은 인덱스값으로 접근이 가능하기 때문에 데이터 쪽에서 유용하게 쓰인다.

profile
구상한것을 구현할 수 있는 개발자가 되고 싶습니다.

0개의 댓글