Python 실습(클래스)

dumbbelldore·2024년 11월 9일
0

zero-base 33기

목록 보기
14/97

1. 회원가입 및 로그인 프로그램

  • 회원가입 클래스와 회원정보관리 클래스를 통해 회원가입 및 로그인 프로그램을 만드시오.
# member.py
class Member():
    def __init__(self, member_id, member_pw):
        self.member_id = member_id
        self.member_pw = member_pw

class MemberManage():
    def __init__(self):
        self.members = {}

    def add_member(self, member):
        self.members[member.member_id] = member.member_pw

    def login_member(self, member_id, member_pw):
        if (member_id in self.members) and (self.members[member_id] == member_pw):
            print(f"> {member_id} 계정으로 정상 로그인되었습니다.")
        else:
            print("> 아이디 또는 비밀번호가 맞지 않습니다.")

    def delete_member(self, member_id, member_pw):
        if self.members[member_id]:
            del self.members[member_id]
            print(f"> {member_id}의 탈퇴가 완료되었습니다.")
        else:
            print(f"> {member_id}의 정보가 존재하지 않습니다.")

    def select_member(self):
        print("> 가입된 회원정보를 출력합니다.")
        for k, v in self.members.items():
            print(f"  - ID: {k}, PW: {v}")
            
# run.py
import member as mb

member_manage = mb.MemberManage()

for i in range(3): # 3인 회원가입
    member_id = input("ID 입력: ")
    member_pw = input("PW 입력: ")
    member = mb.Member(member_id, member_pw)
    member_manage.add_member(member)

print("="*50)
member_manage.select_member() # 전체 회원조회
print("="*50)
member_manage.login_member("kim@gmail.com", "12345") # kim@gmail.com 로그인
print("="*50)
member_manage.login_member("lee@gmail.com", "12345") # lee@gmail.com 로그인
print("="*50)
member_manage.delete_member("kim@gmail.com", "12345") # kim@gmail.com 삭제
print("="*50)
member_manage.select_member() # 전체 회원조회

# run.py 실행결과
# ID 입력: kim@gmail.com
# PW 입력: 12345
# ID 입력: park@gmail.com
# PW 입력: 67890
# ID 입력: lee@gmail.com
# PW 입력: 13579
# ==================================================
# > 가입된 회원정보를 출력합니다.
#   - ID: kim@gmail.com, PW: 12345
#   - ID: park@gmail.com, PW: 67890
#   - ID: lee@gmail.com, PW: 13579
# ==================================================
# > kim@gmail.com 계정으로 정상 로그인되었습니다.
# ==================================================
# > 아이디 또는 비밀번호가 맞지 않습니다.
# ==================================================
# > kim@gmail.com의 탈퇴가 완료되었습니다.
# ==================================================
# > 가입된 회원정보를 출력합니다.
#   - ID: park@gmail.com, PW: 67890
#   - ID: lee@gmail.com, PW: 13579

2. TV 전원 켜기/끄기, 사양 출력 프로그램

  • 인치, 색상, 해상도, 스마트TV 여부, AI기능 여부 속성을 포함하여 두 종류의 클래스(부모, 자식)를 생성하고 간단한 전원 On/Off 기능을 구현하시오.
# tv.py
class NormalTV():
    def __init__(self, inch, color, res):
        self.inch = inch
        self.color = color
        self.res = res
        self.smart_yn = "No"
        self.ai_yn = "No"

    def turnOn(self):
        print("Power is On.")

    def turnOff(self):
        print("Power is Off.")

    def printInfo(self):
        print("> Normal TV Spec.")
        print(f" - 인치: {self.inch}")
        print(f" - 색상: {self.color}")
        print(f" - 해상도: {self.res}")
        print(f" - 스마트TV: {self.smart_yn}")
        print(f" - AI 기능: {self.ai_yn}")

class SmartTV(NormalTV): # NormalTV 상속
    def __init__(self, inch, color, res):
        super().__init__(inch, color, res)
        self.smart_yn = "Yes"
        self.ai_yn = "Yes"
        
    def printInfo(self): # 메소드 오버라이딩
        print("> Smart TV Spec.")
        print(f" - 인치: {self.inch}")
        print(f" - 색상: {self.color}")
        print(f" - 해상도: {self.res}")
        print(f" - 스마트TV: {self.smart_yn}")
        print(f" - AI 기능: {self.ai_yn}")
    
    def checkAIFunc(self): # 메소드 오버로딩
    	print("> Check AI Func: Available")

# run.py
import tv

if __name__ == "__main__":

    print("=== Normal TV ===")
    normal_tv = tv.NormalTV(24, "Red", "Full HD")
    normal_tv.turnOn()
    normal_tv.turnOff()
    normal_tv.printInfo()

    print("=== Smart TV ===")
    smart_tv = tv.SmartTV(48, "Black", "4K")
    smart_tv.turnOn()
    smart_tv.turnOff()
    smart_tv.printInfo()

# run.py 실행결과
# === Normal TV ===
# Power is On.
# Power is Off.
# > Normal TV Spec.
#  - 인치: 24
#  - 색상: Red
#  - 해상도: Full HD
#  - 스마트TV: No
#  - AI 기능: No
# === Smart TV ===
# Power is On.
# Power is Off.
# > Smart TV Spec.
#  - 인치: 48
#  - 색상: Black
#  - 해상도: 4K
#  - 스마트TV: Yes
#  - AI 기능: Yes
# > Check AI Func: Available

3. 도서 관리 프로그램

  • 다음 정보를 참고하여 도서 관리 프로그램을 만드시오.
    - Book 클래스: 속성(name, price, isbn)
    - BookRepo 클래스: 속성(db), 메소드(reg_book, del_book, select_book_list, select_book)
# book.py
class Book():
    def __init__(self, name, price, isbn):
        self.name = name
        self.price = price
        self.isbn = isbn

class BookRepo():
    def __init__(self):
        self.db = dict()

    def reg_book(self, book):
        # 딕셔너리에 객체 자체를 저장
        self.db[book.isbn] = book

    def del_book(self, isbn):
        del self.db[isbn]

    def select_book_list(self):
        for k, v in self.db.items():
            print(f" > Title: {v.name}, Price: {v.price}, ISBN: {v.isbn}")

    def select_book(self, isbn):
        if isbn in self.db:
            print(f" > Title: {self.db[isbn].name}, Price: {self.db[isbn].price}, ISBN: {self.db[isbn].isbn}")
        else:
            print(f"The book isn't registered: {isbn}")

# run.py
from book import Book, BookRepo

if __name__ == "__main__":

    book_repo = BookRepo()
    book_repo.reg_book(Book("Python", 45000, "9999"))
    book_repo.reg_book(Book("Java", 20000, "5555"))
    book_repo.reg_book(Book("Kotlin", 15000, "3333"))

    print("="*50)
    book_repo.select_book_list()
    print("=" * 50)
    book_repo.select_book("5555")
    print("=" * 50)
    book_repo.del_book("5555")
    book_repo.select_book_list()
    print("=" * 50)

# run.py 실행결과
# ==================================================
#  > Title: Python, Price: 45000, ISBN: 9999
#  > Title: Java, Price: 20000, ISBN: 5555
#  > Title: Kotlin, Price: 15000, ISBN: 3333
# ==================================================
#  > Title: Java, Price: 20000, ISBN: 5555
# ==================================================
#  > Title: Python, Price: 45000, ISBN: 9999
#  > Title: Kotlin, Price: 15000, ISBN: 3333
# ==================================================

4. 한-영 사전 사전 프로그램

  • 추상 클래스를 이용하여 단어 등록, 단어 삭제, 단어 수정, 단어 개별조회, 단어 전체조회 기능을 갖는 한-영 사전 프로그램을 만드시오.
# dictionary.py
import abc

class Dictionary(metaclass=abc.ABCMeta): # 추상클래스

    def __init__(self):
        self.db = dict()

    @abc.abstractmethod
    def register_word(self, from_word, to_word):
        pass

    @abc.abstractmethod
    def remove_word(self, word):
        pass

    @abc.abstractmethod
    def update_word(self, target_word, after_word):
        pass

    @abc.abstractmethod
    def select_word(self, word):
        pass

class Kor2EngDictionary(Dictionary): # 상속

    def __init__(self):
        super().__init__()

    def register_word(self, from_word, to_word):
        self.db[from_word] = to_word
        print(f"Registered: {from_word} -> {to_word}")

    def remove_word(self, word):
        del self.db[word]
        print(f"Deleted: {word}")

    def update_word(self, target_word, after_word):
        self.db[target_word] = after_word
        print(f"Updated: {target_word} -> {after_word}")

    def select_word(self, word):
        if word in self.db:
            print(f"Result: {self.db[word]}")
        else:
            print(f"[ERROR] {word} is not registered")

    def select_word_list(self):
        for k, v in self.db.items():
            print(f"{k} -> {v}")

# run.py
import dictionary

if __name__ == '__main__':

    print("=" * 40)

    # 단어 등록
    ke_dict = dictionary.Kor2EngDictionary()
    ke_dict.register_word("아침", "Morning")
    ke_dict.register_word("새벽", "Dawn")
    ke_dict.register_word("제주도", "Jeju Island")
    print("=" * 40)

    # 단어 전제 조회
    ke_dict.select_word_list()
    print("=" * 40)

    # 단어 삭제
    ke_dict.remove_word("아침")
    print("=" * 40)

    # 단어 전체 조회
    ke_dict.select_word_list()
    print("=" * 40)

    # 단어 수정
    ke_dict.update_word("새벽", "Daybreak")
    print("=" * 40)

    # 단어 조회
    ke_dict.select_word("새벽")
    print("=" * 40)

# run.py 실행결과
# ========================================
# Registered: 아침 -> Morning
# Registered: 새벽 -> Dawn
# Registered: 제주도 -> Jeju Island
# ========================================
# 아침 -> Morning
# 새벽 -> Dawn
# 제주도 -> Jeju Island
# ========================================
# Deleted: 아침
# ========================================
# 새벽 -> Dawn
# 제주도 -> Jeju Island
# ========================================
# Updated: 새벽 -> Daybreak
# ========================================
# Result: Daybreak
# ========================================

*이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.

profile
데이터 분석, 데이터 사이언스 학습 저장소

0개의 댓글