ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 타입 힌트(Tpye Hint)
    Python/Today 2025. 9. 3. 09:06
    from typing import Optional
    
    # `typing.Optional`은 파이썬 3.9 이하 버전에서 사용합니다.
    # 파이썬 3.10 이상에서는 `str | None`으로 간단하게 표현 가능합니다.
    
    # 게시글을 생성하는 함수
    def create_post(content: str, title: str | None = None):
        """
        제목과 내용을 받아 게시글을 생성합니다.
        title: 선택적 매개변수로, 문자열이거나 None일 수 있습니다. 기본값은 None입니다.
        content: 필수 매개변수로, 문자열입니다.
        """
        # title이 None인지 확인하는 조건문
        if title is None:
            print("제목이 없는 게시글을 생성합니다.")
            print(f"내용: {content}")
        else:
            print("제목이 있는 게시글을 생성합니다.")
            print(f"제목: {title}")
            print(f"내용: {content}")
    
    # 예제 1: 제목이 있는 경우
    print("--- 제목 있는 게시글 ---")
    create_post(title="파이썬 기초 문법", content="타입 힌트에 대해 배우고 있습니다.")
    
    # 예제 2: 제목을 생략한 경우
    print("\n--- 제목 없는 게시글 ---")
    create_post(content="이것은 제목이 없는 게시글의 내용입니다.")

    'Python > Today' 카테고리의 다른 글

    셀러리(Celery)  (0) 2025.09.05
    @inject  (0) 2025.08.27
    Alembic  (0) 2025.08.26
    Mapped  (0) 2025.08.25
    SQLAlchemy 1.3 vs 2.0 차이점  (0) 2025.08.25
Designed by Tistory.