22. 09. 15.

hyo_d·2022년 9월 15일
0

캠프 12일차

1. 일과

👉 파이썬 문법(이창호 튜터님)

👉 파이썬 과제(클래스 활용, try/except, 리스트 필터 및 정렬)

2. 함수 심화

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
    }

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

2) args / kwargs에 대한 이해

  • args(arguments)와 keyword arguments(kwargs)는 함수에서 인자로 받을 값들의 갯수가
    불규칙하거나 많을 때 주로 사용된다.

  • 인자로 받을 값이 정해져있지 않기 때문에 함수를 더 동적으로 사용할 수 있다.

  • 함수를 선언할 때 args는 앞에 *를 붙여 명시하고, kwargs는 앞에 **를 붙여 명시한다.


  • args 활용하기
number = input()

try:
    int(number)
    10 / number

except ValueError: # int로 변환하는 과정에서 에러가 발생했을 떄
    print(f"{number}은(는) 숫자가 아닙니다.")
    
except ZeroDivisionError: # 0으로 나누면서 에러가 발생했을 때
    print("0으로는 나눌수 없습니다.")
    
except Exception as e: # 위에서 정의하지 않은 에러가 발생했을 때(권장하지 않음)
    print(f"예상하지 못한 에러가 발생했습니다. error : {e}")

# except 문법 또한 if / elif와 같이 연달아서 작성할 수 있다.

  • 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'
}
"""

  • args/kwargs 같이 사용하기
def print_arguments(a, b, *args, **kwargs):
    print(a)
    print(b)
    print(args)
    print(kwargs)
    
print_arguments(
    1, # a
    2, # b
    3, 4, 5, 6, # args
    hello="world", keyword="argument" # kwargs
)

# result print
"""
1
2
(3, 4, 5, 6)
{'hello': 'hello', 'world': 'world'}
"""

3. 패킹과 언패킹

1) 패킹(packing)과 언패킹(unpacking)은 요소들을 묶어주거나 풀어주는 것. list 혹은 dictionary의 값을 함수에 입력할 때 주로 사용된다.

2) 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))
"""

3) 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'
}

"""

4. 객체지향

1) 객체지향이란 객체를 모델링하는 방향으로 코드를 작성하는 것을 의미한다.
영어로는 Object-Oriented Programming이라고 하며 앞자를 따 OOP라고 불려진다.

2) 객체 지향의 특성

  • 캡슐화
    • 특정 데이터의 액세스를 제한해 데이터가 직접적으로 수정되는 것을 방지하며, 검증 된 데이터만을 사용할 수 있다.
  • 추상화
    • 사용되는 객체의 특성 중, 필요한 부분만 사용하고 필요하지 않은 부분은 제거하는 것을 의미한다.
  • 상속
    • 기존에 작성 된 클래스의 내용을 수정하지 않고 그대로 사용하기 위해 사용되는 방식이다.
    • 클래스를 선언할 때 상속받을 클래스를 지정할 수 있다.
  • 다형성
    • 하나의 객체가 다른 여러 객체로 재구성되는 것을 의미한다.
    • 오버라이드, 오버로드가 다향성을 나타내는 대표적인 예시다.

3) 객체 지향의 장/단점

  • 장점
    - 클래스의 상속을 활용하기 때문에 코드의 재사용성이 높아진다.
    - 데이터를 검증하는 과정이 있기 때문에 신뢰도가 높다.
    - 모델링을 하기 수월하다.
    - 보안성이 높다.
  • 단점
    - 난이도가 높다.
    - 코드의 실행 속도가 비교적 느린 편이다.
    - 객체의 역활과 기능을 정의하고 이해해야 하기 때문에 개발 속도가 느려진다.

4) 객체지향 예제 코드

import re

# 숫자, 알파벳으로 시작하고 중간에 - 혹은 _가 포함될 수 있으며 숫자, 알파벳으로 끝나야 한다.
# @
# 알파벳, 숫자로 시작해야 하며 . 뒤에 2자의 알파벳이 와야 한다.
email_regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')

class Attendance:
    count = 0
        
    def attendance(self):
        self.count += 1
    
    @property
    def attendance_count(self):
        return self.count

class Profile(Attendance):
    def __init__(self, name, age, email):
        self.__name = name # __를 붙여주면 class 내부에서만 사용하겠다는 뜻
        self.__age = age
        self.__email = email
    
    @property # 읽기 전용 속성
    def name(self):
        return self.__name
    
    @name.setter # 쓰기 전용 속성
    def name(self, name):
        if isinstance(name, str) and len(name) >= 2:
            print("이름은 2자 이상 문자만 입력 가능합니다.")
            
        else:
            self.__name = name
    
    @property
    def age(self):
        return self.__age
    
    @age.setter
    def age(self, age):
        if isinstance(age, int):
            self.__age = age
            
        else:
            print("나이에는 숫자만 입력 가능합니다.")
        
    @property
    def email(self):
        return self.__email
    
    @email.setter
    def email(self, email):
        if re.fullmatch(email_regex, email):
            self.__email = email
        else:
            print("유효하지 않은 이메일입니다.")
        
    def attendance(self): # override
        super().attendance() # 부모 메소드 사용하기
        self.count += 1
    
    def __str__(self):
        return f"{self.__name} / {self.__age}"
    
    def __repr__(self):
        return f"{self.__name}"

회고

⭐ 오늘은 파이썬 심화 강의 마지막 날이다.. 배운 것은 많은데 아직 머리에서 다 정리가 안 된 느낌이다. 과제를 할 때마다 지난 내용까지 다시 보면서 복습중이다. 풀어야 할 과제가 조금 늦게 나와서 그 전까지 파이썬 문법을 복습하고 장고 원격강의를 살짝 들었다. 개념을 탄탄히해서 장고 강의가 시작할 때 적어도 문법 부분에서는 막히는 것이 없었으면 좋겠다😆

profile
햇병아리

0개의 댓글