예제. 도서관 도메인에서 상속관계 클래스 찾기
요구사항
| 도서관 시스템 요구사항 중 도서관리 도서관 시스템은 도서를 공통적으로 고유 식별자, 제목, 저자, ISBN, 출판사, 출판연도, 장르 정보를 포함하는 기본 도서(Book)로 관리하며, 검색 결과에서는 해당 공통 정보를 출력한다. 도서는 제공 형태에 따라 일반도서(PrintedBook)와 전자도서(EBook)로 구분되며, 일반도서는 서가 위치와 대출 가능 권수를 추가로 관리하고 대출 시 권수가 감소하며 반납 시 증가한다. 전자도서는 파일 형식, 접근 URL, 동시 이용 가능 인원 정보를 추가로 관리하며, 이용 시작 시 현재 이용 인원이 증가하고 종료 시 감소하도록 한다. |
예상 클래스 다이어그램
예상 코드
더보기
class Book:
def __init__(self, id, title, author, isbn, publisher, publish_year, genre):
self.__id = id
self.__title = title
self.__author = author
self.__isbn = isbn
self.__publisher = publisher
self.__publish_year = publish_year
self.__genre = genre
def display_info(self):
print("===========(도서정보)==========")
print(f" 제목: {self.__title}")
print(f" 저자: {self.__author}")
print(f" ISBN: {self.__isbn}")
print(f" 출판사: {self.__publisher}")
print(f"출판년도: {self.__publish_year}")
print(f" 장르: {self.__genre}")
print("==============================")
class PrintedBook(Book):
def __init__(self, id, title, author, isbn, publisher, publish_year, genre, location, available_copies):
super().__init__(id, title, author, isbn, publisher, publish_year, genre)
self.location = location
self.available_copies = available_copies
def borrow(self):
if self.available_copies > 0:
self.available_copies -= 1
print("일반도서 대출 완료")
else:
print("대출 불가")
def return_book(self):
self.available_copies += 1
print("일반도서 반납 완료")
class EBook(Book):
def __init__(self, id, title, author, isbn, publisher, publish_year, genre, file_format, access_url, concurrent_limit):
super().__init__(id, title, author, isbn, publisher, publish_year, genre)
self.file_format = file_format
self.access_url = access_url
self.concurrent_limit = concurrent_limit
self.current_users = 0
def borrow(self):
if self.current_users < self.concurrent_limit:
self.current_users += 1
print("==> 전자도서 이용 시작")
else:
print("==> 동시 이용 초과")
def return_book(self):
if self.current_users > 0:
self.current_users -= 1
print("==> 전자도서 이용 종료")
book1 = PrintedBook(1, "Python", "홍길동", "111", "한빛", 2024, "IT", "A-1", 2)
book2 = EBook(2, "AI", "이몽룡", "222", "길벗", 2025, "IT", "PDF", "www.book.com", 3)
book1.display_info()
book1.borrow()
book1.borrow()
book1.borrow()
book2.display_info()
book2.borrow()
book2.borrow()
book2.borrow()
book2.borrow()
실습. 키오스크 도메인에서 상속관계 클래스 찾기
도서관 시스템의 예상 클래스 다이어그램과 예상 코드를 참조하여 아래 요구사항에서 상속관계의 클래스를 도출하여 클래스 다이어그램을 그리고, 파이썬 코드로 구현하시오.
| 카페 키오스크 시스템은 판매하는 모든 메뉴항목에 대해 공통적으로 고유 식별자, 메뉴명, 가격, 판매 상태 정보를 관리하며, 메뉴 목록 조회 시 해당 공통 정보를 출력한다. 메뉴는 종류에 따라 커피(Coffee)와 디저트(Dessert)로 구분되며, 커피류는 카페인 함량과 온도(Hot/Ice) 정보를 추가로 관리하고, 디저트류는 칼로리와 보관 방법 정보를 추가로 관리한다. 모든 메뉴는 판매 상태가 ‘판매중’일 때만 주문이 가능하다. |
제출1. 클래스 다이어그램
- ppt, https://app.diagrams.net/에서 작성 가능
제출 2. 파이썬 코드
- 1. 제출 1을 파이썬으로 구현한 클래스 코드
- 정의한 클래스는 클래의 모든 속성을 출력하는 print_all() 매소드를 각각 정의한다.
- 2. (위) 1번에서 구현한 클래스 코드의 인스턴스를 각각 만들어서 부모클래스, 자식 클래스들의 print_all() 메소드를 호출하는 코드를 작성한다.
- 3. (위) 1번, 2번에서 구현한 클래스에 대해 클래스의 의미에 맞는 메소드 하나를 부모클래스에 추가하고, 자식클래스에서 Method Overriding하는 예를 추가한다. 필요시 super()를 사용한다.
클래스다이어그램 예시
코드 예시
더보기
class MenuItem:
def __init__(self, item_id, name, price, available_stock):
self._id = item_id
self._name = name
self._price = price
self._available_stock = available_stock
def order(self, order_qty):
# 주문전 체크
if self._available_stock == 0:
print(f"{self._name}은(는) 품절입니다. 주문할 수 없습니다.")
return
elif self._available_stock < order_qty:
print(f"{self._name}은(는) {self._available_stock}개만 주문 가능합니다. 수량을 줄려주세요.")
return
# 주문처리
self._available_stock -= order_qty
print(f"{self._name} 주문 완료! 남은 재고: {self._available_stock}")
if self._available_stock == 0:
print(f"{self._name}은(는) 품절되었습니다.")
def print_all(self):
print()
print("========== 메뉴 ==========")
print(f"ID: {self._id}")
print(f"이름: {self._name}")
print(f"가격: {self._price}원")
print(f"재고: {self._available_stock}")
class Coffee(MenuItem):
def __init__(self, item_id, name, price, caffeine_amount, temperature_type):
super().__init__(item_id, name, price, available_stock=3)
self.__affeine_amount = caffeine_amount
self.__temperature_type = temperature_type
def print_all(self):
super().print_all()
print(f"카페인 함량: {self._caffeine_amount}mg")
print(f"온도 타입: {self._temperature_type}")
class Dessert(MenuItem):
def __init__(self, item_id, name, price, calories_kcal, storage_type):
super().__init__(item_id, name, price, available_stock=3)
self.__calories_kcal = calories_kcal
self.__storage_type = storage_type
def print_all(self):
super().print_all()
print(f"칼로리: {self._calories_kcal}kcal")
print(f"보관 방법: {self._storage_type}")
# 객체 생성
coffee1 = Coffee(item_id=1, name="아메리카노", price=4500, caffeine_amount=150, temperature_type="HOT")
dessert1 = Dessert(item_id=2, name="치즈케이크", price=5500, calories_kcal=320, storage_type="냉장보관")
# 커피주문
# 초기 상태 출력
coffee1.print_all()
# 주문 4번 시도
print("\n[아메리카노 주문]")
coffee1.order(1)
coffee1.order(1)
coffee1.order(2)
coffee1.order(1) # 품절 후 주문 시도
# 최종 상태 출력
coffee1.print_all()
# 디저트 주문
# 초기 상태 출력
dessert1.print_all()
# 주문 4번 시도
print("\n[아메리카노 주문]")
dessert1.order(1)
dessert1.order(2)
dessert1.order(1) # 품절 후 주문 시도
# 최종 상태 출력
dessert1.print_all()
'[2] 객체지향 프로그래밍 설계(파이썬) > 5주차. 상속' 카테고리의 다른 글
| 5.1 [개념] 클래스 특징 3. 상속 (0) | 2025.01.17 |
|---|

