본문 바로가기

python

class random - 예제 (로또 번호 출력기)

*하단에 해설 포함

# 클래스의 포함관계 : 로또 번호 출력기

import random

class LottoBall:
    def __init__(self, num):
        self.num = num

class LottoMachine:
    def __init__(self):
        self.ballList =[]
        for i in range(1, 46):
            self.ballList.append(LottoBall(i))  #포함
            
    def selectBalls(self):
        # 볼 섞기 전 출력하기
        for a in range(45):
            print(self.ballList[a].num, end = ' ')
        random.shuffle(self.ballList)  # 섞기
        print()
        for a in range(45):
            print(self.ballList[a].num, end = ' ')
        
        return self.ballList[0:6]
            
class LottoUi:
    def __init__(self):
        self.machine = LottoMachine() # 포함
        
    def playLotto(self):
        input('로또를 시작하려면 엔터키를 누르세요')
        selectedBalls = self.machine.selectBalls()
        print('\n당첨 번호')
        for ball in selectedBalls:
            print('%d '%ball.num, end = ' ')

if __name__ == '__main__':
    # lo = LottoUi()
    # lo.playLottho()
    LottoUi().playLotto()

로또를 시작하려면 엔터키를 누르세요
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 
11 6 3 19 14 24 29 2 7 17 28 30 45 31 38 34 12 5 20 36 16 23 39 4 44 10 43 37 26 13 42 33 8 1 18 9 22 15 40 25 32 41 35 21 27 
당첨 번호
11  6  3  19  14  24  

 

 

class LottoMachine

생성자에서 리스트 자료형인 ballList를 만들고 for 반복문과 append() 함수를 사용해서 1~45의 숫자를 담아준다. 이때 LottoBall type으로 담아준다.

selectBalls 메소드에서 반복문으로 그대로 출력해준다.

이후 random.suffle()을 사용해서 섞어준 뒤 다시 반복문으로 출력해준다. 이때는 순서가 랜덤으로 배정되어 있다.

리턴값은 앞에서 랜덤 순서로 정렬된 리스트를 [0:6] 슬라이싱해서 돌려준다.

import random

class LottoBall:
    def __init__(self, num):
        self.num = num

class LottoMachine:
    def __init__(self):
        self.ballList =[]
        for i in range(1, 46):
            self.ballList.append(LottoBall(i))  #포함
            
    def selectBalls(self):
        # 볼 섞기 전 출력하기
        for a in range(45):
            print(self.ballList[a].num, end = ' ')
        random.shuffle(self.ballList)  # 섞기
        print()
        for a in range(45):
            print(self.ballList[a].num, end = ' ')
        
        return self.ballList[0:6]

 

class LottoUi

생성자에서 LottoMachine()을 포함시켜준다. 

LottoMachine을 실행시켜 슬라이싱된 리턴값을 받아오고 이것을 반복문으로 출력해준다.

class LottoUi:
    def __init__(self):
        self.machine = LottoMachine() # 포함
        
    def playLotto(self):
        input('로또를 시작하려면 엔터키를 누르세요')
        selectedBalls = self.machine.selectBalls()
        print('\n당첨 번호')
        for ball in selectedBalls:
            print('%d '%ball.num, end = ' ')

 

LottoUi 클래스에 있는 playLotto() 메소드를 실행한다

if __name__ == '__main__':
    # lo = LottoUi()
    # lo.playLottho()
    LottoUi().playLotto()