반응형
아래와 같이 차량의 정보를 관리해야하는 경우 우리는 여러 방법을 사용할 수 있다.
대표적인 파이썬의 자료구죠인 리스트, 딕셔너리를 통한 관리를 알아보고 어떤 단점이 있는지
클래스를 사용하면 어떻게 보완할 수 있는지 직접 구현해보자.
- 변수에 할당하여 관리
직관적이고 수정이 쉽지만 차량이 많아질수록 더 많은 변수를 만들어 관리해야하는 불편함이 있다. (=하드코딩)
# 차량1
car_company_1 = 'Ferrari'
car_detail_1 = [
{'color': 'White'},
{'horsepower': 400},
{'price': 8000}
]
# 차량2
car_company_2 = 'Bmw'
car_detail_2 = [
{'color': 'Black'},
{'horsepower': 270},
{'price': 5000}
]
# 차량3
car_company_3 = 'Audi'
car_detail_3 = [
{'color': 'Silver'},
{'horsepower': 300},
{'price': 6000}
]
- 리스트 구조로 관리
정보의 카테고리별 분류가 가능하지만 인덱스 번호로 접근 시 관리가 불편하다.
car_company_list = ['Ferrari', 'Bmw', 'Audi']
car_detail_list = [
{'color': 'White', 'horsepower': 400, 'price': 8000},
{'color': 'Black', 'horsepower': 270, 'price': 5000},
{'color': 'Silver', 'horsepower': 300, 'price': 6000}
]
# 인덱스 번호로 삭제할 경우
del car_company_list[1]
del car_detail_list[1]
- 딕셔너리 구조
코드 반복은 지속되고, 키의 중첩 문제가 있다.
정렬이 불편하다.
car_dicts = [
{'car_company': 'Ferrari', 'car_detail': {'color': 'white', 'horsepower': 400, 'price': 8000}},
{'car_company': 'Bmw', 'car_detail': {'color': 'Black', 'horsepower': 270, 'price': 5000}},
{'car_company': 'Audi', 'car_detail': {'color': 'Silver', 'horsepower': 300, 'price': 6000}}
]
# 삭제 할 경우
del car_dicts[1]
클래스 사용
클래스 중심 = 데이터 중심
개별 객체로 관리하기 때문에 유지/관리가 쉽다.
코드의 재사용성이 증가하여, 코드 반복을 최소화 할 수 있다.
class Car():
def __init__(self, company, details):
self._company = company
self._details = details
def __str__(self):
return 'str: {} - {}'.format(self._company, self._details)
def __repr__(self):
return 'repr: {} - {}'.format(self._company, self._details)
def __reduce__(self):
pass
car1 = Car('Ferrari', {'color': 'White', 'horsepower': 400, 'price': 8000})
car2 = Car('Bmw', {'color': 'Black', 'horsepower': 270, 'price': 5000})
car3 = Car('Audi', {'color': 'Silver', 'horsepower': 300, 'price': 6000})
클래스 사용으로 활용할 수 있는데 메서드에 대해 알아보자.
- str : 비공식적으로 사용자 레벨의 출력을 원할 경우(반복문 등에서 사용)
def __str__(self):
return 'str: {} - {}'.format(self._company, self._details)
- repr : 개발자 레벨이 출력을 원할 경우
만약 str이 정의되어 있지 않은 상태에서 str을 출력할 경우 python은 repr을 반환해준다.
def __repr__(self):
return 'repr: {} - {}'.format(self._company, self._details)
반응형