ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Function, kwargs
    python/기본 2022. 4. 29. 18:37
    # num: int = 10
    
    def add_num(a: int, b: int) -> int:
        """add two int
    
        :param a: first param
        :param b: second param
        :return: sum value
        """
        return a + b
    
    
    print(help(add_num))
    
    r = add_num(1, 2)
    print(r)
    
    s = add_num('X', 'Y')
    print(s)  # XY working!!!
    
    
    ####################################################################
    def menu(x, y, z='Z'):
        print(x, y, z)
    
    
    menu(x='a', y='b')
    
    
    ####################################################################
    # list 나 dictionary 를 default 값으로 지정하지 말자
    def buggy_func(x, l=[]):
        l.append(x)
        return l
    
    
    r = buggy_func(100)
    print(r)  # [100]
    
    r = buggy_func(100)
    print(r)  # [100, 100]
    
    
    def fixed_func(x, l=None):
        if l is None:
            l = []
        l.append(x)
        return l
    
    
    r = fixed_func(100)
    print(r)  # [100]
    
    r = fixed_func(100)
    print(r)  # [100]
    
    
    ####################################################################
    # 위치 인수의 튜플화
    
    def say_something(word, *args):
        print(word)  # Hi
        print(args)  # ('Mike', 'Nancy')
    
        for arg in args:
            print(arg)  # Mike Nancy
    
    
    say_something('Hi', 'Mike', 'Nancy')
    
    # 아래 처럼 호출도 가능
    t = ('Mike', 'Nancy')
    say_something('Hi', *t)
    
    
    ####################################################################
    # 키워드 인수의 사전화
    
    def menu(**kwargs):
        print(kwargs)  # {'x': 1, 'y': 2}
        for k, v in kwargs.items():
            print(k, v)
    
    
    menu(x=1, y=2)
    
    # 아래 처럼 호출도 가능
    d = {'x': 1, 'y': 2}
    menu(**d)
    
    
    def complex_menu(food, *args, **kwargs):
        print(food)
        print(args)
        print(kwargs)
    
    
    complex_menu('banana', 'apple', 'orange', drink='coffee')
    '''
    banana
    ('apple', 'orange')
    {'drink': 'coffee'}
    '''
    
    
    ####################################################################
    # 함수내 함수
    
    def outer(a, b):
        def plus(c, d):
            return c + d
    
        r = plus(a, b)
        print(r)
    
    
    outer(1, 2)

    'python > 기본' 카테고리의 다른 글

    Decorator / contextmanager  (0) 2022.04.29
    Closure  (0) 2022.04.29
    range, enumerate, zip  (0) 2022.04.29
    For  (0) 2022.04.29
    Input  (0) 2022.04.29

    댓글

Designed by Tistory.