내배캠/TIL

TIL/32/20230425

woongpang 2023. 4. 25. 21:08
728x90

함수 심화

  • 인자에 기본값 지정해주기
    • def calc(num1, num2, option=None): # 인자로 option이 들어오지 않는 경우 기본값 할당
  • args / kwargs에 대한 이해
    • args(arguments)와 keyword arguments(kwargs)는 함수에서 인자로 받을 값들의 갯수가 불규칙하거나 많을 때 주로 사용됩니다.
    • 인자로 받을 값이 정해져있지 않기 때문에 함수를 더 동적으로 사용할 수 있습니다.
    • 함수를 선언할 때 args는 앞에 *를 붙여 명시하고, kwargs는 앞에 **를 붙여 명시합니다.

패킹과 언패킹

  • 패킹과 언패킹이란?
    • 패킹(packing)과 언패킹(unpacking)은 단어의 뜻 그대로 요소들을 묶어주거나 풀어주는 것을 의미합니다.
    • list 혹은 dictionary의 값을 함수에 입력할 때 주로 사용됩니다.
  • list에서의 활용
  • dictionary에서의 활용

객체지향

  • 객체지향(Object-Oriented Programming)이란??
    • 객체지향이란 객체를 모델링하는 방향으로 코드를 작성하는 것을의미합니다. 영어로는 Object-Oriented Programming이라고 하며 앞자를 따 OOP라고 불려집니다.
    • 파이썬 뿐만이 아닌, 다양한 언어들에서 프로젝트를 개발하며 사용되는 개발 방식 중 하나입니다.
  • 객체지향의 특성
    • 캡슐화
      • 특정 데이터의 액세스를 제한해 데이터가 직접적으로 수정되는 것을 방지하며, 검증 된 데이터만을 사용할 수 있습니다.
    • 추상화
      • 사용되는 객체의 특성 중, 필요한 부분만 사용하고 필요하지 않은 부분은 제거하는 것을 의미합니다.
    • 상속
      • 상속은 기존에 작성 된 클래스의 내용을 수정하지 않고 그대로 사용하기 위해 사용되는 방식입니다.
      • 클래스를 선언할 때 상속받을 클래스를 지정할 수 있습니다.
    • 다형성
      • 하나의 객체가 다른 여러 객체로 재구성되는 것을 의미합니다.
      • 오버라이드, 오버로드가 다향성을 나타내는 대표적인 예시입니다.
  • 객체지향의 장/단점
    • 장점
      • 클래스의 상속을 활용하기 때문에 코드의 재사용성이 높아집니다.
      • 데이터를 검증하는 과정이 있기 때문에 신뢰도가 높습니다.
      • 모델링을 하기 수월합니다.
      • 보안성이 높습니다.
    •  단점
      • 난이도가 높습니다.
      • 코드의 실행 속도가 비교적 느린 편입니다.
      • 객체의 역활과 기능을 정의하고 이해해야 하기 때문에 개발 속도가 느려집니다.
  • 객체지향 예제 코드

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에서의 활용

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

"""

객체지향 예제 코드

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}"
728x90