- Python 강의 | 4. Python 심화 [함수 심화 / 패킹과 언패킹 / 객체지향]
1. 함수 심화
[인자에 기본값 지정해주기]
변수 지정과 유사하지만 방식이 다름.
변수 지정은 단순히 값만 지정해 주는 느낌이라면 함수 선언시 인자의 기본값 설정은 동작이나 과정, 식 등을 지정해 줄 수 있다.
👉 함수 선언 전 인자에 기본값을 설정해준다.
EXPRESSION = {
0: lambda x, y: x + y ,
1: lambda x, y: x - y ,
2: lambda x, y: x * y ,
3: lambda x, y: x / y
}
👉 인자로 option이 들어오지 않는 경우 기본값 할당
def calc(num1, num2, option=None):
"""
option
- 0: 더하기
- 1: 빼기
- 2: 곱하기
- 3: 나누기
"""
return EXPRESSION[option](num1, num2) if option in EXPRESSION.keys() else False
print(calc(10, 20)) # False 👉 option 값이 없기때문에 False
print(calc(10, 20, 0)) # 30
print(calc(10, 20, 1)) # -10
print(calc(10, 20, 2)) # 200
print(calc(10, 20, 3)) # 0.5
[args / kwargs에 대한 이해]
args / kwargs는 함수에서 인자로 받을 값들의 갯수가 불규칙하거나 많을 때 주로 사용됩니다.
- args 활용하기
- 주로 변수 설정에 이용 (변수로 받을 값들의 갯수가 불규칙하거나 많을 때 )
- args 선언시 앞에 * 을 붙여 → *args 로 표현한다.
def add(*args): 👉 불특정 다수의 변수들 : args = (1, 2, 3, 4)
result = 0
for i in args: 👉 선언되는 args 마다 결과가 다르게
result += i
return result
print(add()) # 0 👉 값마다 결과값이 다르게 변화하고 있다.
print(add(1, 2, 3)) # 6
print(add(1, 2, 3, 4)) # 10
- kwargs 활용하기
- 주로 딕셔너리 선언에 사용 (dict으로 받을 key:value들의 갯수가 불규칙하거나 많을 때 )
- kwargs 선언시 앞에 ** 을 붙여 → **kwargs 로 표현한다.
def set_profile(**kwargs):
profile = {}
profile["name"] = kwargs.get("name", "-") 👉 프로필 key 값에 kwargs의 key값 가져와
profile["gender"] = kwargs.get("gender", "-")
profile["birthday"] = kwargs.get("birthday", "-")
profile["age"] = kwargs.get("age", "-")
profile["phone"] = kwargs.get("phone", "-")
profile["email"] = kwargs.get("email", "-")
return profile
profile = set_profile( 👉 set_profile의 정해지지 않은 kwargs의 dict 정해줘
name="lee",
gender="man",
age=32,
birthday="01/01",
email="python@sparta.com",
)
print(profile) 👉 위에서 저장된 key:value 프로필에 저장
🟰 결과값은:
{
'name': 'lee',
'gender': 'man',
'birthday': '01/01',
'age': 32,
'phone': '-',
'email': 'python@sparta.com'
}
- args / kwargs 같이 사용해보기
- 동시에 선언 할 수 있다.
def print_arguments(a, b, *args, **kwargs): 👉 *args, **kwargs 동시 선언
print(a)
print(b)
print(args)
print(kwargs)
print_arguments( 👉 함수 print_arguments에 아래 순서대로 변수에 저장됨
1, # a
2, # b
3, 4, 5, 6, # args
hello="world", keyword="argument" # kwargs
)
🟰 결과값은:
1
2
(3, 4, 5, 6)
{'hello': 'hello', 'world': 'world'}
2. 패킹과 언패킹
말 그대로, 요소들을 패킹 or 언패킹 하는것 (묶 or 풀)
주로 list 혹은 dictionary의 값을 함수에 입력할 때 사용한다.
[list 패킹과 언패킹]
list의 모든 요소를 패키징 할 땐, *리스트명 으로 표현
def add(*args):
result = 0
for i in args: 👉 1.args는 변수를 일일히 선언해 줘야 함
result += i
return result
numbers = [1, 2, 3, 4]
print(add(*numbers))
👉 2. '1,2,3,4' 를 일일히 쓰지 않고 number로 리스트 선언 후 패킹하여 *number로 표현
[dictionary 패킹과 언패킹]
dictionary의 모든 요소를 패키징 할 땐, **딕셔너리명 으로 표현
def set_profile(**kwargs):
profile = {}
profile["name"] = kwargs.get("name", "-")
profile["gender"] = kwargs.get("gender", "-")
profile["birthday"] = kwargs.get("birthday", "-")
profile["age"] = kwargs.get("age", "-")
profile["phone"] = kwargs.get("phone", "-")
profile["email"] = kwargs.get("email", "-")
return profile
user_profile = { 👉 **kwargs의 dict 설정
"name": "lee",
"gender": "man",
"age": 32,
"birthday": "01/01",
"email": "python@sparta.com",
}
print(set_profile(**user_profile))
👉 설정한 dict 패킹하여 삽입
👉 'profile = set_profile()' 로 삽일할 dict을 일일히 set_profile값으로 변경 후 삽입하지 않아도 set_profile(**user_profile) 으로 패킹하여 선언 가능
""" 아래 코드와 동일
profile = set_profile(
name="lee",
gender="man",
age=32,
birthday="01/01",
email="python@sparta.com",
)
"""
🟰 결과값은:
{
'name': 'lee',
'gender': 'man',
'birthday': '01/01',
'age': 32,
'phone': '-',
'email': 'python@sparta.com'
}
'woncoding > TIL' 카테고리의 다른 글
| TIL | 9.19.월 [Python 복습 🐢] (0) | 2022.09.19 |
|---|---|
| TIL | 9.16.금 [Python 복습 🐢] (0) | 2022.09.19 |
| TIL | 9.14.수 [Python 심화] (0) | 2022.09.14 |
| TIL | 9.13.화 [Python 심화] (0) | 2022.09.13 |
| TIL | 9.10.토 [Git / GitHub] (0) | 2022.09.12 |