lambda(람다) -2, def 함수 문법과 lambda 문법의 차이

2023. 5. 22. 01:21학습/python

def 로 굳이 함수 이름을 지정하지 않고
'기능자체'를 argument에 집어 넣겠다가 lambda 문법의 제작의도이다.
lambda {argument 들}:  return 받을 값(기능)

전편 글에서 람다의 정의와 제작의도, 구조를 배웠다.

 

이번 글에서는 lambda 와 def 함수 문법의 차이를 다뤄볼 것이다.

 

 

1. argument 의 갯수

def str_add(a,b,c,d):
    print(a+b+c+d)
str_add('q','w','e','r') # qwer
str_add2 = lambda a,b,c,d: print(a+b+c+d)
str_add2('q','w','e','r') # qwer

둘다 많은 수의 argument 를 받을 수 있다.

 

2. argument에 default 값 선언

def str_add(a,b,c='평',d='와드'):
    print(a+b+c+d)
str_add('q','w') # qw평와드
str_add2 = lambda a,b,c='평',d='와드': print(a+b+c+d)
str_add2('q','w') #qw평와드

둘다 모두 default 값을 선언할 수 있다.

 

3. type hint (lambda 불가능)

def str_add(a:str,b:str,c:str,d:str):
    print(a+b+c+d)
str_add('q','w','e','r') # qwer
str_add2 = lambda a:str, b:str,c:str,d:str : print(a+b+c+d)
'''
str_add2 = lambda a:str, b:str, c:str, d:str : print(a+b+c+d)
                              ^
SyntaxError: invalid syntax
'''

다른 문법으로는 가능하지만 lambda 자체로는 불가능하다.

 

4.필요한 연산이 많거나 결과를 위한 경우의 수가 나뉘어져 있으면, lambda 로는 여러 줄의 code 함수를 만들 수 없음.

 

lambda 는 한 statement로만 return할 수밖에 없는 함수만 만들 수 있다.
def multiply(a,b):
    if type(b) == int or type(b) == float:
        return a*b
    elif type(b) == str:
        return a * float(b)
    elif type(b) == list:
        return [a*i for i in b]
print(multiply(41,2))  # 82
print(multiply(36,"3")) # 108.0
print(multiply(3,[1,2,3]))  #[3,6,9]
lambda a,b: a* b if type(b) == int or type(b) == float \
        elif type(b) == str a * float(b) \
        elif type(b) == list [a*i for i in b]
'''
line 2
    elif type(b) == str a * float(b) \
       ^
SyntaxError: invalid syntax
'''
multiply = lambda a,b : a*b \
    if type(b)==int or type(b)==float \
    else a*float(b) if type(b)==str \ ### float 로 형변환 후 곱셈
    else [a*i for i in b] if type(b)==list \
    else None

print(multiply(41,2)) #82
print(multiply(36,"3")) #108.0
print(multiply(3,[1,2,3])) # [3,6,9]

lambda 는 한 줄로 retunr 하는 함수를 이름 없이 기능만 쓰도록 하는 함수.

제작의도에 맞게 간단한 기능들을 lambda 처리하도록 하자.

 

정리

함수를 더 세분화 된 단위로 나누어 다룰 수 있음

-> 기능의 더  세분화된 분리로 다형성, 캡슐화 용이

 

기능 구현과 계싼 수행을 보다 가시성 있게 분리 가능

728x90