타입 힌트

Python 중급 객체 지향 프로그래밍

Jake Roach

Data Engineer

타입 힌트 없는 코드

class Student:
    def __init__(self, name, student_id, tuition_balance):
        self.name = name
        self.student_id = student_id
        self.tuition_balance = tuition_balance

# Trying to create a class can be tricky
walker = Student("Sarah Walker", 319921, 15000)
  • student_id는 정수여야 할까요?
  • tuition_balance는 float, 정수, 아니면 문자열이어야 할까요?
  • walker를 만든 뒤, 나중에 코드에서 그 타입을 어떻게 기억할까요?
Python 중급 객체 지향 프로그래밍

타입 힌트

객체 정보(타입)를 코드에 추가하는 선택적 도구

  • 읽기·디버깅이 쉬움
  • 엔터프라이즈급 Python 역량을 보여주는 가장 좋은 방법 중 하나
  • 인터프리터가 강제하지 않음
  • 내장 타입 키워드, typing 라이브러리, 사용자 정의 클래스
# 변수에 타입 힌트 추가
gpa: float = 3.92

# 함수/메서드 정의에 타입 힌트 추가 def check_grades(year: str) -> List[int]: ...
# 사용자 정의 클래스도 사용 가능 students: Dict[str, Student] = {...}
Python 중급 객체 지향 프로그래밍

내장 타입 키워드로 타입 힌팅

# 선언적 로직에 타입 힌트 사용
name: str = "Frost"  # Before: name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# 함수/메서드 정의에 타입 힌트 사용
def get_schedule(semester: str) -> dict:
    ...
  • 구문: variable: type 사용
  • 선언적, 함수/메서드 시그니처 명확화
  • 반환 타입 표시는 def .... () -> type:
Python 중급 객체 지향 프로그래밍

typing 라이브러리

typing은 더 많은 타입 힌트 도구를 제공하는 라이브러리입니다

  • List, Dict, Tuple
  • 최상위 객체와 그 요소 타입 모두 힌트
from typing import List, Dict

student_names: List[str] = ["Morgan", "Chuck", "Anna"]
student_gpas: Dict[str, float] = {
    "Casey": 3.71,
    "Sarah": 4.0
}
  • Any, Set, Iterator, Callable
Python 중급 객체 지향 프로그래밍

사용자 정의 클래스와 타입 힌팅

class Student:
    def __init__(self, name: str, student_id: int, tuition_balance: float) -> None:
        self.name: str = name
        self.student_id: int = student_id
        self.tuition_balance: float = tuition_balance

    def get_course(self, course_id: str) -> Course:
        ...
        return course
# Use Student and Course to type hint
walker: Student = Student("Sarah Walker", 319921, 15000)
data_science: Course = walker.get_course("TDM-20100")
Python 중급 객체 지향 프로그래밍

객체 타입 확인하기

# walker: Student = Student("Sarah Walker", 319921, 15000)
print(type(walker))
<class '__main__.Student'>
# data_science: Course = walker.get_course("TDM-20100")
print(type(data_science))
<class '__main__.Course'>
Python 중급 객체 지향 프로그래밍

Lass uns üben!

Python 중급 객체 지향 프로그래밍

Preparing Video For Download...