ABOUT ME

Computer, Music, Video.

Today
Yesterday
Total
  • 파이썬에서 *, ** (별표, asterisk)
    Python/이것저것 파이썬 2025. 3. 30. 13:13
    반응형

    1. *args (가변 위치 인자)

    *args는 여러 개의 인자를 튜플 형태로 받을 때 사용됩니다.

    def add_numbers(*args):
        print(args)  # 튜플 형태로 전달됨
        return sum(args)
    
    print(add_numbers(1, 2, 3, 4))
    # (1, 2, 3, 4)
    # 10
    
    print(add_numbers(10, 20))
    # (10, 20)
    # 30

    2. **kwargs (가변 키워드 인자)

    **kwargs는 여러 개의 키워드 인자를 딕셔너리 형태로 받을 때 사용됩니다.

    def print_info(**kwargs):
        print(kwargs)  # 딕셔너리 형태로 전달됨
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    
    print_info(name="Alice", age=25, city="New York")
    
    # {'name': 'Alice', 'age': 25, 'city': 'New York'}
    # name: Alice
    # age: 25
    # city: New York

    3. 함수 호출 시 * & ** 사용

    함수 호출 시 *와 **를 이용한 언패킹.
    *와 **는 함수 호출 시에도 리스트/딕셔너리를 개별 인자로 변환하는 데 사용됩니다.

    리스트(튜플) → 개별 인자 변환 (*)

    def multiply(a, b, c):
        return a * b * c
    
    numbers = [2, 3, 4]
    print(multiply(*numbers))  # multiply(2, 3, 4)와 동일 → 24

    딕셔너리 → 개별 키워드 인자 변환 (**)

    def introduce(name, age, city):
        print(f"이름: {name}, 나이: {age}, 도시: {city}")
    
    person = {"name": "Alice", "age": 25, "city": "Seoul"}
    introduce(**person)  # introduce(name="Alice", age=25, city="Seoul")과 동일

    4. 리스트/튜플을 변수에 할당할 때 * 사용

    *를 사용한 언패킹 (여러 값 받기)

    a, *b, c = [1, 2, 3, 4, 5]
    print(a)  # 1
    print(b)  # [2, 3, 4]
    print(c)  # 5

    5. 함수 정의에서 *을 사용해 위치 전용 인자 지정

    def example(a, b, *, c, d):
        return a + b + c + d
    
    # example(1, 2, 3, 4)  # 오류 (c, d는 키워드 인자로만 전달 가능)
    print(example(1, 2, c=3, d=4))  # 올바른 호출

    6. 이런 식의 언패킹도 가능 

    DEFAULT_FONT = font.nametofont("TkDefaultFont")
    print(DEFAULT_FONT.actual())
    # {'family': '.AppleSystemUIFont', 'size': 13, 'weight': 'normal', 'slant': 'roman', 'underline': 0, 'overstrike': 0}
    BOLD_FONT = font.Font(**{**DEFAULT_FONT.actual(), 'weight': 'bold', 'underline': 1})

    DEFAULT_FONT를 이용해 BOLD_FONT 라는 새로운 객체를 생성할 때 기존 값을 재사용하고 싶을 때
    이런 식으로 딕셔너리를 이용할 수 있습니다. 

    딕셔너리를 언패킹 한 뒤, 2개의 키값을 추가하고 이를 다시 딕셔너리로 만들어 인자로 전달합니다. 
    반복문을 이용해 처리한다면 꽤 긴 코드가 됩니다.  

    반응형
Designed by Tistory.