JUNG씨 2022. 9. 15. 19:54

📍파이썬 문법 - 함수 심화

▪️인자에 기본값 지정해주기 => 함수를 선언할 때 괄호 안에 인자를 미리 설정해줄 수 있다. 그러면 나중에 함수를 호출해서 실행할 때 그 인자를 넘겨받아 실행시킬 수 있다. 

 

# 함수를 선언할 때 인자에 기본값을 지정해줄 수 있습니다.
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
    }

def calc(num1, num2, option=None): # 인자로 option이 들어오지 않는 경우 기본값 할당
    """
    option
     - 0: 더하기
     - 1: 빼기
     - 2: 곱하기
     - 3: 나누기
    """
    return EXPRESSION[option](num1, num2) if option in EXPRESSION.keys() else False

print(calc(10, 20))    # 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 활용하기

def add(*args):
    # args = (1, 2, 3, 4)
    result = 0
    for i in args:
        result += i
        
    return result

print(add())           # 0
print(add(1, 2, 3))    # 6
print(add(1, 2, 3, 4)) # 10

 

- kwargs 활용하기

def set_profile(**kwargs):
    """
    kwargs = {
        name: "lee",
        gender: "man",
        age: 32,
        birthday: "01/01",
        email: "python@sparta.com"
    }
    """
    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

profile = set_profile(
    name="lee",
    gender="man",
    age=32,
    birthday="01/01",
    email="python@sparta.com",
)

print(profile)
# result print
"""
{   
    'name': 'lee',
    'gender': 'man',
    'birthday': '01/01',
    'age': 32,
    'phone': '-',
    'email': 'python@sparta.com'
}
"""

 

▪️패킹과 언패킹

요소들을 묶어주거나 풀어주는 것. list 혹은 dictionary의 값을 함수에 입력할 때 주로 사용됨.

 

- list에서의 활용

def add(*args):
    result = 0
    for i in args:
        result += i
        
    return result

numbers = [1, 2, 3, 4]

print(add(*numbers)) # 10

"""아래 코드와 동일
print(add(1, 2, 3, 4))
"""

 

- 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 = {
    "name": "lee",
    "gender": "man",
    "age": 32,
    "birthday": "01/01",
    "email": "python@sparta.com",
}

print(set_profile(**user_profile))
""" 아래 코드와 동일
profile = set_profile(
    name="lee",
    gender="man",
    age=32,
    birthday="01/01",
    email="python@sparta.com",
)
"""

# result print
"""
{
    'name': 'lee',
    'gender': 'man',
    'birthday': '01/01',
    'age': 32,
    'phone': '-',
    'email': 'python@sparta.com'
}

"""

 

 

▪️객체지향(Object-Oriented Programming-OOP)객체지향이란 객체를 모델링하는 방향으로 코드를 작성하는 것.

  • 객체지향의 특성
    • 캡슐화 : 특정 데이터의 액세스를 제한해 데이터가 직접적으로 수정되는 것을 방지하며, 검증 된 데이터만을 사용할 수 있다.
    • 추상화 : 사용되는 객체의 특성 중, 필요한 부분만 사용하고 필요하지 않은 부분은 제거하는 것.
    • 상속 : 기존에 작성 된 클래스의 내용을 수정하지 않고 그대로 사용할 수 있다 .클래스를 선언할 때 상속받을 클래스를 지정할 수 있다. 
    • 다형성 : 하나의 객체가 다른 여러 객체로 재구성되는 것. ex) 오버라이드, 오버로드
  • 객체지향의 장/단점
    • 장점
      • 클래스의 상속-> 코드 재사용 가능
      • 높은 신뢰도 -> 데이터를 검증하는 과정.
      • 모델링 용이.
      • 보안성 높아짐.
    • 단점
      • 난이도가 높다.
      • 코드의 실행 속도가 비교적 느린 편.
      • 객체의 역활과 기능을 정의하고 이해해야 하기 때문에 개발 속도가 느려진다.

 

 

 

 

p.s. 주말에.... 복습..... 필수....... ㅎ___ㅎ