TIL 12 | More Complex Function Parameters & Nested Function

Hyeonju L.·2020년 11월 26일
0

Python

목록 보기
8/9

1. More Complex Function Parameters

사전에 정확히 필요한 parameter 수와 구조를 알 수 없는 경우, dictionary를 parameter로 받아서 사용 가능하다.

  • 장점: 옵션만 간단히 설정할 수 있다
  • 단점: 옵션을 dictionary로 받아야 하기때문에 옵션을 추가하지 않는 경우에도 비어있는 dictionary를 넘겨줘야 하고, 다른 타입의 값을 넘겨주는 오류 발생 가능성도 존재.
def buy_A_car(options):
	print(f"다음 사양의 자동차를 구입하십니다:")
    
    for option in options:
    	print(f"{option} : {options[option]}")
    
options = {"seat":"가죽", "blackbox":"최신"} # 옵션만 간단하게 설정
buy_A_car(options)   

결과

1) Keyworded variable length of arguments

  • keyword arguments(키워드 인수)인데 그 수가 유동적으로 변할 수 있는 인수
  • parameter명 앞에 **로 시작.

일반 keyword arguments와의 차이점
- argument 수를 0부터 N까지 유동적으로 넘겨줄 수 있음
- Keyword가 정해져있지 않기 때문에 원하는 keyword 사용 가능
- dictionary 형태로 지정됨

def buy_A_car(**kwargs):
    print(f"다음 사양의 자동차를 구입하십니다:")

    for option in kwargs:
        print(f"{option} : {kwargs[option]}") 
        
buy_A_car(seat="가죽", blackbox="최신", tint="yes") # 호출 시

2) Non-keyworded variable length of arguments(=variable arguments)

  • 직전에서 언급했던 Keyworded variable length of arguments와 동일하지만 keyword를 사용하지 않고 순서대로 값을 전달하는 방식.
  • *로 선언되며 tuple로 변환되어 함수에 전달됨.

3) Mixing args and kwargs

Keyworded variable arguments & Variable arguments 둘 다 사용하여 함수 정의.
둘 다 사용하면 어떠한 형태와 수의 argument도 허용가능한 함수가 되어 parameter에 있어 굉장히 유동적인 함수가 됨.

def do_something(*args, **kwargs):

4) 예제

  • sum_of_numbers 함수 구현: argument로 주어지는 모든 수를 합한 값 리턴하기
def sum_of_numbers(*args):
	
    sum = 0
    if args == 0:
    	return 0
    for arg in args:
    	sum += arg
    return sum
  • what_is_my_full_name 함수 구현: 주어진 parameter 중 first_name과 last_name 이라는 parameter 조합하여 full name 리턴하기
def what_is_my_full_name(**kwargs):

    if "first_name" in kwargs and "last_name" in kwargs:
        return f"""{kwargs["last_name"]} {kwargs["first_name"]}"""
    elif "first_name" in kwargs and "last_name" not in kwargs:
        return f"""{kwargs["first_name"]}"""
    elif "first_name" not in kwargs and "last_name" in kwargs:
        return f"""{kwargs["last_name"]}"""
    else:
        return "Nobody"

2. Nested function

함수도 함수 안에 중첩되어 선언할 수 있다!

def parent_function()"
    def child_function():
        print("this is a child function")
    child_function()
parent_function() 	# 결과: "this is a child function"
  • 중첩함수를 사용하는 이유는?!

1) 가독성
반복되는 코드를 함수로 정의해서 효과적으로 코드를 관리할 수 있다.

def print_all_elements(list_of_things):
    def print_each_element(things):   # 중첩함수 선언
        for thing in things:
            print(thing)

    if len(list_of_things) > 0:
        print_each_element(list_of_things)
    else:
        print("There is nothing!")

2) closure
중첩 함수가 부모 함수의 변수나 정보를 가두어 사용하는 것.
부모함수의 변수를 외부로부터 직접적인 접근은 격리하면서도 중첩함수를 통해 부모함수의 변수를 사용한 연산은 가능하게 해준다.

def generate_power(base_number):
    def nth_power(power):
        return base_number ** power


    return nth_power
 
calculate_power_of_two = generate_power(2)
calculate_power_of_two(7)   # 결과: 128

profile
What you think, you become. What you feel, you attract. What you imagine, you create.

0개의 댓글