A ship in harbor is safe, but that is not what ships are built for.

개발일지/AI 캠프

내일배움캠프 AI - 12일차 TIL, 2022.09.15

플리피나리 2022. 9. 16. 09:37
반응형

스파르타 코딩클럽 내일배움캠프 AI 웹개발자양성과정 3회차

2022.09.15. 12일차 - TIL

 

 

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
  • args와 kwargs : 함수에서 인자로 받을 값들의 갯수가 불규칙하거나 많을 때 주로 사용, 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'}
"""
  • 패킹과 언패킹 : 요소들을 묶어주거나 풀어주는 것을 의미
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))
"""

######################################################
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'
}

"""
  • 캡슐화 : 특정 데이터의 액세스를 제한해 데이터가 직접적으로 수정되는 것을 방지하며, 검증 된 데이터만을 사용
  • 추상화 : 필요한 부분만 사용하고 필요하지 않은 부분은 제거하는 것
  • 상속 : 기존에 작성 된 클래스의 내용을 수정하지 않고 그대로 사용하기 위해 사용되는 방식
  • 다형성 : 하나의 객체가 다른 여러 객체로 재구성 -> 오버라이드, 오버로드
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}"
반응형