📌 파이썬 연습문제 [클래스]
📋 회원가입 클래스와 회원 정보를 관리하는 클래스를 만들고 회원가입 로그인 기능을 구현
💡Member 클래스
class Member:
def __init__(self, id, pw):
self.id = id
self.pw = pw
💡MemberRegister 클래스
class MemberRegister:
def __init__(self):
self.member = {}
def login(self, id, pw):
isMember = id in self.member
if isMember and self.member[id] == pw:
print(f'{id} : Log-in Success!')
return True
else:
print(f'{id} does not exist.')
return False
def viewMember(self):
for key in self.member.keys():
print(f'ID: {key}')
print(f'ID: {self.member[key]}')
def deleteMember(self, id, pw):
isMember = id in self.member
if isMember and self.member[id] == pw:
del self.member[id]
self.viewMember()
else:
print(f'{id} does not exist.')
---------------------------------------------------
💡main
mRegister = MemberRegister()
print('\t 회원가입 \t')
for i in range(3):
id = input('ID : ')
pw = input('PW : ')
member = Member(id, pw)
mRegister.member.update({member.id: member.pw})
mRegister.viewMember()
print('로그인')
while True:
id = input('ID : ')
pw = input('PW : ')
if mRegister.login(id, pw):
break
print('회원 관리')
id = input('ID : ')
pw = input('PW : ')
mRegister.deleteMember(id, pw)
📋 상속을 이용한 TV 클래스
💡NormalTv 클래스
class NormalTv:
def __init__(self, inch=32, color='black', res='full-HD'):
self.inch = inch
self.color = color
self.resolution = res
self.smartTv = 'off'
self.aiTv = 'off'
def turnOn(self):
print('Turn On')
def turnOff(self):
print('Turn Off')
def printTvInfo(self):
print(f'TV SIZE : {self.inch} ')
print(f'TV COLOR : {self.color} ')
print(f'TV RESOLUTION : {self.resolution} ')
print(f'SMART TV : {self.smartTv} ')
print(f'AI TV : {self.aiTv} ')
💡Tv4K 클래스
class Tv4K(NormalTv):
def __init__(self, i, c, r='4k'):
super().__init__(i, c, r)
def setSmartTv(self, smart):
self.smartTv = smart
💡Tv8K 클래스
class Tv8K(NormalTv):
def __init__(self, i, c, r='8k'):
super().__init__(i, c, r)
def setSmartTv(self, smart):
self.smartTv = smart
def setAiTv(self, ai):
self.aiTv = ai
---------------------------------------------------
💡main
normal = NormalTv()
normal.printTvInfo()
print('-' * 20)
tv4 = Tv4K(64, 'blue')
tv4.setSmartTv('On')
tv4.printTvInfo()
tv4.turnOn()
print('-' * 20)
tv8 = Tv8K(128, 'red')
tv8.setAiTv('On')
tv8.setSmartTv('On')
tv8.printTvInfo()
tv8.turnOff()
📋도서 관리 프로그램
💡Book 클래스
class Book:
def __init__(self, n, p, i):
self.name = n
self.price = p
self.isbn = i
💡BookRepository 클래스
class BookRepository:
def __init__(self):
self.books = {}
def registBook(self, book):
self.books[book.isbn] = book
def removeBook(self, isbn):
if isbn in self.books.keys():
del self.books[isbn]
else:
print(f'존재하지 않는 책입니다.')
def printBooksInfo(self):
for isbn in self.books.keys():
book = self.books[isbn]
print(f'책 이름 : {book.name}')
print(f'{book.name} 가격 : {book.price}')
print(f'{book.name} isbn : {book.isbn}')
def printBookInfo(self, isbn):
if isbn in self.books.keys():
book = self.books[isbn]
print(f'책 이름 : {book.name}')
print(f'{book.name} 가격 : {book.price}')
print(f'{book.name} isbn : {book.isbn}')
else:
print(f'{isbn}이 존재하지 않습니다.')
---------------------------------------------------
💡main
books = BookRepository()
for i in range(3):
name = input('책 이름 : ')
price = input(f'{name} 가격 : ')
isbn = input(f'{name} isbn : ')
book = Book(name, price, isbn)
books.registBook(book)
books.printBooksInfo()
print('-' * 30)
isbn = input('책의 정보 열람 : ')
books.printBookInfo(isbn)
print('-' * 30)
isbn = input('삭제 할 책의 isbn : ')
books.removeBook(isbn)
print('-' * 30)
books.printBooksInfo()
📋추상 클래스를 이용해서 한/영, 한/일 사전 만들기
from abc import ABCMeta
from abc import abstractmethod
💡추상클래스 AbsDictionary
class AbsDictionary(metaclass=ABCMeta):
def __init__(self):
self.wordDic = {}
@abstractmethod
def registWord(self, w1, w2):
pass
@abstractmethod
def removeWord(self, w1):
pass
@abstractmethod
def updateWord(self, w1, w2):
pass
@abstractmethod
def searchWord(self, w1):
pass
def printDic(self):
for k in self.wordDic.keys():
print(f'{k} : {self.wordDic[k]}')
💡클래스 KorToEng
class KorToEng(AbsDictionary):
def printDic(self):
print('Korean to English')
super().printDic()
def registWord(self, w1, w2):
print(f'단어 등록 : {w1} to {w2}')
self.wordDic[w1] = w2
def removeWord(self, w1):
if w1 in self.wordDic.keys():
print(f'ENG 단어 삭제 : delete {w1}')
del self.wordDic[w1]
else:
print('존재하지 않는 단어입니다.')
def updateWord(self, w1, w2):
print(f'ENG 단어 업데이트 : update {w1} to {w2}')
self.wordDic.update({w1: w2})
def searchWord(self, w1):
print(f'{w1}를 번역 중입니다.')
if w1 in self.wordDic.keys():
print(f'{w1} -> {self.wordDic[w1]}')
💡클래스 KorToJpa
class KorToJpa(AbsDictionary):
def printDic(self):
print('Korean to Japanese')
super().printDic()
def registWord(self, w1, w2):
print(f'단어 등록 : {w1} to {w2}')
self.wordDic[w1] = w2
def removeWord(self, w1):
if w1 in self.wordDic.keys():
print(f'JP 단어 삭제 : delete {w1}')
del self.wordDic[w1]
else:
print('존재하지 않는 단어입니다.')
def updateWord(self, w1, w2):
print(f'JP 단어 업데이트 : update {w1} to {w2}')
self.wordDic.update({w1: w2})
def searchWord(self, w1):
print(f'{w1}를 번역 중입니다.')
if w1 in self.wordDic.keys():
print(f'{w1} -> {self.wordDic[w1
---------------------------------------------------
💡main
korea = ['귤', '딸기', '메론', '고구마', '석류']
jp = ['みかん', 'イチゴ', 'メロン', 'さつまいも', 'ザクロ']
eng = ['Tangerines', 'strawberries', 'melon', 'sweet potatoes', 'pomegranate']
ktj = KorToJpa()
kte = KorToEng()
for i in range(len(korea)):
ktj.registWord(korea[i], jp[i])
for i in range(len(korea)):
kte.registWord(korea[i], eng[i])
ktj.printDic()
kte.printDic()
ktj.removeWord('귤')
kte.removeWord('고구마')
ktj.updateWord('메론', 'Under inspection')
kte.updateWord('메론', 'Under inspection')
ktj.searchWord('석류')
kte.searchWord('석류')
ktj.printDic()
kte.printDic()
📋주사위 게임 클래스를 만들고 게임 결과 출력
import random
💡클래스 Dice
class Dice:
def __init__(self):
self.com = None
self.user = None
def setCnum(self):
print('[Dice] setCnum()')
return random.randint(1, 6)
def setUnum(self):
print('[Dice] setUnum()')
return random.randint(1, 6)
def startGame(self):
print('[Dice] startGame()')
self.com = self.setCnum()
self.user = self.setUnum()
self.printResult()
def printResult(self):
if self.com == self.user:
print(f'컴퓨터 vs 유저 : {self.com} vs {self.user} >> 무승부')
elif self.com > self.user:
print(f'컴퓨터 vs 유저 : {self.com} vs {self.user} >> Computer Win')
else:
print(f'컴퓨터 vs 유저 : {self.com} vs {self.user} >> User Win')
---------------------------------------------------
💡main
dice = Dice()
dice.startGame()
📋주사위 게임 클래스를 만들고 게임 결과 출력
import random
from time import sleep
💡클래스 Car
class Car:
def __init__(self, n='Formula', c='black', s=200):
self.name = n
self.color = c
self.maxSpeed = s
self.distance = 0
def printCarInfo(self):
print(f'Car is {self.name}')
print(f'Color is {self.color}')
print(f'Max Speed is {self.maxSpeed}')
def controlSpeed(self):
return random.randint(0, self.maxSpeed)
def getDistanceForHour(self):
return self.controlSpeed() * 1
class CarRacing:
def __init__(self):
self.cars = []
def startRacing(self):
for i in range(10):
print(f'Racing : {i + 1}바퀴')
for car in self.cars:
car.distance += car.getDistanceForHour()
sleep(0.3)
self.printCurrentCarDistance()
print()
def printCurrentCarDistance(self):
for car in self.cars:
print(f'{car.name} : {car.distance} \t\t ', end='')
def addCar(self, car):
self.cars.append(car)
---------------------------------------------------
💡main
car1 = Car()
car2 = Car('Grand', 'green', 300)
car3 = Car('Sports', 'red', 250)
car4 = Car('Stock', 'gray', 150)
car5 = Car('Touring', 'blue', 280)
racing = CarRacing()
racing.addCar(car1)
racing.addCar(car2)
racing.addCar(car3)
racing.addCar(car4)
racing.addCar(car5)
racing.startRacing()
📋mp3 플레이어 클래스 만들고 노래 등록 후 재생
import random
from time import sleep
💡클래스 Player
class Player:
def __init__(self):
self.songList = []
self.isLoop = False
def addSong(self, song):
self.songList.append(song)
def play(self):
cnt = 0
if self.isLoop:
while self.isLoop:
for song in self.songList:
cnt += 1
song.printSongInfo()
sleep(song.time)
self.setIsLoop(int(input('반복 (1), 종료 (0) : ')))
else:
for song in self.songList:
song.printSongInfo()
sleep(song.time)
def suffle(self):
random.shuffle(self.songList)
def setIsLoop(self, loop):
self.isLoop = loop
💡클래스 Song
class Song:
def __init__(self, title, singer, time):
self.title = title
self.siger = singer
self.time = time
def printSongInfo(self):
print(f'{self.title} - {self.siger} [{self.time}]')
---------------------------------------------------
💡main
s1 = Song('Butterfly', 'Numcha', 4)
s2 = Song('Youth', 'Jade', 3)
s3 = Song('slam', '10-FEET', 4)
s4 = Song('Weekend', 'TAEYEON', 3)
s5 = Song('Ditto', '뉴진스', 2)
player = Player()
player.addSong(s1)
player.addSong(s2)
player.addSong(s3)
player.addSong(s4)
player.addSong(s5)
player.setIsLoop(True)
player.suffle()
player.play()