회고
- 한 5~6시간정도 자판기에 대한 코드를 짰다. 클래스를 구분하는 것부터 각 클래스에 기능을 넣고 하나로 출력하는과정을 구현하며 전체적으로 생각하는 힘이 길러졌다. 하지만 아직까지 하나하나 쪼개서 코드를 구현하는 것은 가능하나,,, 마지막 하나로 합쳐 출력하는 과정에서 많이 버벅인다. 전체적인 코드구성이 잘못된 것일까 아니면 파이썬에 대한 기초가 부족한 것일까? 뭐가 됐든 둘다 보강해야겠다. 그래도 자판기, 도서대여 시스템을 구현해낸 뿌듯한 하루다😊
필기
- 오늘은 자판기만들기 대회를 해서 수업내용이 많지 않다.
- 리눅스 환경에 대해 배웠는데 새로운 환경이 신기했다.
과제
자판기_객체지향
- 만들면서 참 생각이 많았다.
-- 클래스를 어떤 기준으로 나눌 것인지.
-- 이렇게 하면 복잡한데 더 간단하게 만들 수 없는 지
- 결과적으로 자판기를 만들어냈으나 만족스럽지는 않다. 너무 코드를 우겨넣어 놓은 것 같달까? 그렇지만 한편으로는 만족스럽다. 비록 마지막 main()함수에 AI친구들의 도움을 받긴 했지만 다음엔 내가 적을 수 있다는 확신이 들었다. 이것만으로도 쓴 5시간이 아깝지않다.
import pickle
class ProductVending:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
self.payMoney = 0
self.change = 0
def process(self):
print("\n===계산시작===")
while True:
self.payMoney = int(input("돈을 넣으세요 : "))
self.change = self.payMoney - self.price
if self.change >= 0:
return
else:
self.change < 0
print("돈을 다시 넣어주세요")
def printInfoManager(self):
print(f"상품명 : {self.name}", end = "\t")
print(f"상품가격 : {self.price}", end = "\t")
print(f"상품재고 : {self.count}")
def printInfoBuyer(self):
print(f"상품명 : {self.name}", end = "\t")
print(f"상품가격 : {self.price}")
def printCalBuyer(self):
print(f"상품명 : {self.name}", end = "\t")
print(f"상품가격 : {self.price}", end = "\t")
print(f"넣은돈 : {self.payMoney}", end = "\t")
print(f"거스름돈 : {self.change}")
print("===계산완료===")
class ProductVendingManager():
def __init__(self, productList):
self.productList = productList
def append(self):
name = input("추가할 상품명 : ")
price = int(input("추가할 상품가격 : "))
count = int(input("추가할 상품개수 : "))
product = ProductVending(name,price,count)
self.productList.append(product)
def search(self):
name = input("검색할 상품명 : ")
resultList = list(filter(lambda x: name in x.name, self.productList))
if len(resultList) == 0:
print("검색한 상품이 없습니다.")
for index, name in enumerate(resultList):
print(f"번호 : {index}", end = "\t")
name.printInfoManager()
def remove(self):
name = input("검색할 상품명 : ")
resultList = list(filter(lambda x: name in x.name, self.productList))
if len(resultList) == 0:
print("검색한 상품이 없습니다.")
for index, name in enumerate(resultList):
print(f"번호 : {index}", end = "\t")
name.printInfoManager()
sel = int(input("삭제할 상품의 번호를 입력해주세요 : "))
self.productList.remove(resultList[sel])
def modify(self):
name = input("검색할 상품명 : ")
resultList = list(filter(lambda x: name in x.name, self.productList))
if len(resultList) == 0:
print("검색한 상품이 없습니다.")
for index, name in enumerate(resultList):
print(f"번호 : {index}", end = "\t")
name.printInfoManager()
sel = int(input("수정할 상품의 번호를 입력해주세요 : "))
item = resultList[sel]
item.name = input("상품명 : ")
item.price = int(input("가격 : "))
item.count = int(input("재고 : "))
print("===수정완료===")
def save(self):
with open("product1", "wb") as f:
pickle.dump(self.productList, f)
print("===저장완료===")
def load(self):
with open("product1", "rb") as f:
self.productList = pickle.load(f)
self.printInfoManager()
print("===불러오기완료===")
def printAll(self):
for p in self.productList:
p.printInfoManager()
if len(self.productList) == 0:
print("등록된 상품이 없습니다.")
print("===전체상품출력완료===")
class ProductVendingBuyer:
def __init__(self, productList):
self.productList = productList
def printAll(self):
if len(self.productList) == 0:
print("상품이 없습니다.")
return
for p in self.productList:
p.printInfoBuyer()
print("\n===전체상품출력완료===\n")
def choice(self):
while True:
name = input("구매할 상품명 : ")
resultList = list(filter(lambda x: name in x.name, self.productList))
if len(resultList) == 0:
print("상품이 없습니다. 다시 시도해주세요.")
return
for index, item in enumerate(resultList):
print(f"번호 : {index}", end="\t")
item.printInfoBuyer()
try:
sel = int(input("구매할 상품의 번호를 입력해주세요 : "))
if sel < 0 or sel >= len(resultList):
print("잘못된 번호입니다.")
return
except ValueError:
print("숫자를 입력해주세요.")
return
item = resultList[sel]
if item.count <= 0:
print("해당 상품은 품절입니다.")
return
item.process()
item.printCalBuyer()
item.count -= 1
return
def main():
product_list = [
ProductVending("콜라", 2000, 5),
ProductVending("사이다", 1800, 3),
ProductVending("물", 1000, 10)
]
admin = ProductVendingManager(product_list)
buyer = ProductVendingBuyer(product_list)
while True:
print("=== 자판기 메인 메뉴 ===")
print("1. 구매자 모드")
print("2. 관리자 모드")
print("0. 종료")
sel = input("번호 선택: ")
if sel == "1":
while True:
print("\n===구매자 메뉴===")
print("1. 상품 보기")
print("2. 상품 구매")
print("0. 돌아가기")
b_sel = input("번호 선택: ")
if b_sel == "1":
buyer.printAll()
elif b_sel == "2":
buyer.choice()
elif b_sel == "0":
break
else:
print("잘못된 입력입니다.")
elif sel == "2":
pwcount = 3
success = False
while pwcount > 0:
pw = input("비밀번호를 입력하세요 : ")
if pw == "admin":
print("로그인 성공")
success = True
break
else:
pwcount -= 1
print(f"비밀번호가 틀립니다. 남은 기회는 {pwcount}번 입니다.")
if not success:
print("로그인 실패. 메인 메뉴로 돌아갑니다.")
continue
while True:
print("\n===관리자 메뉴===")
print("1. 상품 목록 보기")
print("2. 상품 추가")
print("3. 상품 수정")
print("4. 상품 삭제")
print("5. 저장")
print("6. 불러오기")
print("0. 돌아가기")
sel2 = input("번호 선택: ")
if sel2 == "1":
admin.printAll()
elif sel2 == "2":
admin.append()
elif sel2 == "3":
admin.modify()
elif sel2 == "4":
admin.remove()
elif sel2 == "5":
admin.save()
elif sel2 == "6":
admin.load()
elif sel2 == "0":
break
else:
print("잘못된 입력입니다.")
elif sel == "0":
print("자판기를 종료합니다.")
break
else:
print("잘못된 입력입니다.")
if __name__ == "__main__":
main()
복습

gpt를 이용한 유사예제
도서관 책대여_객체지향
- 어찌어찌 만들긴 했는데 몇가지 오류가있다.

- 클래스들이 같은 bookList를 공유하게 셋팅을 했는데..... 파일 저장/불러오기(pickle)을 사용해서 불러오면 값이 저장되지 않는다. 어떻게 해야할까 대체.....

- 이해했다. 현재 코드는 pickle에 저장되어 있는 값을 self.bookList에 덮어 씌우기 때문에 예전 값이 불러와지는 것이다. 저기서 clear()를 하는게 이해가 안됐는데 리스트이 객체가 바뀌지않아 다른곳에서 참조중인 객체와 연결이 유지된다고한다.. 참 신기하다.
import pickle
class Book:
def __init__(self, title, author, stock):
self.title = title
self.author = author
self.stock = stock
def printInfo(self):
print(f"제목 : {self.title}, 저자 : {self.author}, 재고 : {self.stock}")
class Admin:
def __init__(self, bookList):
self.bookList = bookList
def append(self):
title = input("제목 : ")
author = input("저자 : ")
stock = int(input("재고 : "))
book = Book(title, author, stock)
self.bookList.append(book)
def search(self):
title = input("검색할 책 이름 : ")
resultList = list(filter(lambda x: title in x.title, self.bookList))
if not resultList:
print("검색한 책이 없습니다.")
else:
for index, title in enumerate(resultList):
print(f"{index}", end = "\t")
title.printInfo()
def remove(self):
title = input("검색할 책 이름 : ")
resultList = list(filter(lambda x: title in x.title, self.bookList))
if not resultList:
print("검색한 책이 없습니다.")
else:
for index, title in enumerate(resultList):
print(f"{index}", end = "\t")
title.printInfo()
sel = int(input("삭제할 책의 인덱스번호를 입력하세요 : "))
self.bookList.remove(resultList[sel])
def modify(self):
title = input("검색할 책 이름 : ")
resultList = list(filter(lambda x: title in x.title, self.bookList))
if not resultList:
print("검색한 책이 없습니다.")
else:
for index, title in enumerate(resultList):
print(f"{index}", end = "\t")
title.printInfo()
sel = int(input("수정할 책의 인덱스번호를 입력하세요 : "))
item = resultList[sel]
item.title = input("수정할 책 이름 : ")
item.author = input("수정할 책 저자 : ")
item.stock = int(input("수정할 책 재고 : "))
def save(self):
with open("book1", "wb") as f:
pickle.dump(self.bookList, f)
print("===저장완료===")
def load(self):
with open("book1", "rb") as f:
self.bookList = pickle.load(f)
self.printAll()
print("===불러오기완료===")
def printAll(self):
if not self.bookList:
print("등록된 책이 없습니다.")
for b in self.bookList:
b.printInfo()
class User:
def __init__(self, bookList):
self.bookList = bookList
def borrow(self):
title = input("검색할 책 이름 : ")
resultList = list(filter(lambda x: title in x.title, self.bookList))
if not resultList:
print("검색한 책이 없습니다.")
return
else:
for index, title in enumerate(resultList):
print(f"{index}", end = "\t")
title.printInfo()
sel = int(input("빌릴 책의 인덱스번호를 입력하세요 : "))
item = resultList[sel]
if item.stock > 0:
print("책을 대여했습니다. 7일 뒤 반납해주세요!")
item.stock -= 1
else:
print("재고가 없습니다.")
class Main:
def __init__(self, bookList):
self.bookList = bookList
def main(self):
pw = 1234
errorcount = 0
while True:
print("=========================")
print("1. 책을 빌리시겠습니까?")
print("2. 관리자모드")
print("0. 종료")
print("=========================")
sel = int(input("번호를 입력해주세요 : "))
if sel not in [0, 1, 2]:
print("번호를 다시 입력하세요")
continue
elif sel == 1:
user = User(self.bookList)
user.borrow()
elif sel == 2:
inpw = int(input("비밀번호 : "))
if pw != inpw:
print("=== 로그인 실패 ===")
errorcount += 1
if errorcount == 3:
print("3회 이상 실패. 선택 모드로 돌아갑니다.")
continue
else:
print("=== 로그인 성공 ===")
admin = Admin(self.bookList)
while True:
print("===관리자 메뉴===")
print("1. 책 목록 출력")
print("2. 책 추가")
print("3. 책 검색")
print("4. 책 삭제")
print("5. 책 수정")
print("6. 책 저장")
print("7. 책 불러오기")
print("0. 이전으로")
adm_sel = int(input("선택 : "))
if adm_sel == 1:
admin.printAll()
elif adm_sel == 2:
admin.append()
elif adm_sel == 3:
admin.search()
elif adm_sel == 4:
admin.remove()
elif adm_sel == 5:
admin.modify()
elif adm_sel == 6:
admin.save()
elif adm_sel == 7:
admin.load()
elif adm_sel == 0:
break
else:
print("잘못된 입력입니다.")
elif sel == 0:
print("프로그램을 종료합니다.")
break
if __name__ == "__main__":
bookList = []
lib = Main(bookList)
lib.main()