본문 바로가기
카테고리 없음

[Python] Type Annotation

by 까다로운오리 2024. 3. 31.

 

타입 어노테이션이란?

-  변수, 상수 선언 시에 어떤 타입으로 저장할 것인지 알려주는 방법

- 코드 가독성과 효율성이 좋아짐

 

def add(a: int, b: int) -> int
	return a + b
    
    
add("1", "2") #에러가 발생하진 않음 but '12'가 출력

add.__annotations__ #타입 어노테이션 확인

 

 

from typing import List

names: List[str] = ["Alice", "Bob", "Charlie"]

user: Dict[str, str] = {"name": "Alice", "email": "alice@example.com"}


# 클래스 
class Student:
    def __init__(self, name: str, grades: List[int]) -> None:
        self.name = name
        self.grades = grades

    def get_average_grade(self) -> float:
        return sum(self.grades) / len(self.grades)

 

 

출처 : https://wikidocs.net/194289#_2