업무에 파이썬 활용할 줄 알기
Day17 | 중급 | 퀴즈 프로젝트와 OOP의 장점 본문
Day17 | 중급 | 퀴즈 프로젝트와 OOP의 장점
SEO 데이터분석가 2023. 12. 28. 14:51파이썬에서 클래스를 만드는 방법
PascalCase
camelCase
snake_case
속성, 클래스 생성자, __init__() 함수 활용하기
attribute를 만드는 방법은 일반적인 변수를 만드는 방법과 비슷하지만,
object(객체)에 할당해주는 것이기 때문에 [ object명.attribute명 = "" ] 로 만들어준다
만약에 변수가 많고, 매번 새로운 user, 즉 object를 만들어줄 때마다
아래와 같이 수많은 attribute를 만들어줘야한다면 실수하기 쉽다
클래스에서 객체를 만들 때 어떻게 하면 이런 시작 정보들을 모두 명시할 수 있을까?
그렇게 하려면 생성자(Constructor)라는 것을 이해해야한다.
생성자는 청사진의 일부로, 객체가 생성될 때 무슨 일이 일어나야 하는지 명시할 수 있게 한다
이것은 객체 초기화로도 알려져있다.
_init__(객체 초기화) 을 활용하여 attribute(속성) 만들어주는 법
__init__(객체 초기화) 을 활용하여 attribute(속성) 만들어주기 예시
attribute(속성) 디폴트값을 설정해주는 방법
클래스에 메소드 추가하기
예를 들어 race mode에 들어갔을 때 5개의 시트를 2개로 줄이는 mothod를 만들어준다고 가정하자.
method 만들어주고, 실행하기 예시
인스타그램 팔로우 클릭했을 때의 상황이라고 가정해보자.
user_1.follow(user_2) method를 실행시킴으로서
user_1의 followers가 1명 늘고, user_2의 following이 1명 늘었음을 알 수 있다.
Question 클래스, Question 객체 리스트를 만들어주는 이유 이해하기
왜 이미 만들어져있는 리스트를 굳이 클래스를 만들어서 다시 리스트를 만들어주는거지?
퀴즈 프로젝트 1부: 질문 클래스 만들기
퀴즈 프로젝트 2부: 데이터로부터 질문 객체 리스트 만들기
we're going to be creating a question bank of question objects
notice how we can create a question object by using the name of the class and then giving it some inputs for the question and the answer
My solution
from question_model import Question
from data import question_data
# Write a for loop to iterate over the question_data.
# Create a Question object from each entry in question_data.
# Append each Question object to the question_bank
question_bank = []
for i in range(len(question_data)):
qi = question_data[i]["text"]
ai = question_data[i]["answer"]
question_bank.append(Question(qi, ai))
print(question_bank[0].text)
모범답안
new_question = Question(question_text, question_answer) 과 같이 object를 만들어주는 방법을 썼다는 것에 주목
여전히 잘 모르겠는건
data.py의 question_data변수의 리스트를
왜 굳이 Question클래스, object를 만들어주는걸 활용해서 question_bank리스트를 다시 만들어주는거지?
question_bank = []
for question in question_data:
question_text = question["text"]
question_answer = question["answer"]
new_question = Question(question_text, question_answer)
question_bank.append(new_question)
print(question_bank[0].text)
퀴즈 프로젝트 3부: 퀴즈브레인과 next_question() 메소드
메소드 부분 My solution
# Create a class called QuizBrain.
# Write an __init__() method.
# Initialise the question_number to 0.
# Initialise the question_list to an input.
class QuizBrain:
def __init__(self, q_list):
self.question_number = 0
self.question_list = q_list
# this method needs to retrieve the item at the current question number from the question_list
# and once you have this item, use the input function to show the user the question text and ask for the user's answer.
def next_question(self, q_list, q_num):
self.q = q_list[q_num]
self.ask = input(f"Q.{q_num}: {q}. (True/False)?: ")
모범답안
# Create a class called QuizBrain.
# Write an __init__() method.
# Initialise the question_number to 0.
# Initialise the question_list to an input.
class QuizBrain:
def __init__(self, q_list):
self.question_number = 0
self.question_list = q_list
# this method needs to retrieve the item at the current question number from the question_list
# and once you have this item, use the input function to show the user the question text and ask for the user's answer.
def next_question(self):
current_question = self.question_list[self.question_number]
input(f"Q.{self.question_number}: {current_question.text} (True/False): ")
Q. question_number는 어떻게 갱신이 되는걸까?
main.py에서의 결과
퀴즈 프로젝트 4부: 새로운 질문을 계속 보여주는 방법
요구사항
# Create method called still_has_questions().
# Return a boolean depending on the value of question_number.
# Use the While loop
My solution
모범답안
퀴즈 프로젝트 5부: 답변을 확인하고 점수 유지하기
모범답안
OOP의 이점: 새로운 질문을 얻기 위해 Open Trivia DB 활용하기
이 수업에서 들었던 첫 의문이 여기에서 풀렸다
왜 Question 클래스를 만들어주는건지
question_bank가 다른 형태로 변경이 되더라도 QuizBrain는 수정해주지 않아도 되는 이점
And this really brings about some of the advantages of Object Oriented
Programming. Notice how only our main.py file actually has knowledge of how each
of these classes work and behave. Our QuizBrain actually didn't need to be touched at all
when we changed our data over. This is modularity at its best.
We're able to completely switch up the question data to a different language,
to a different topic, to a different format, and the quiz brain doesn't care.
All it has to concern itself with is how to track which question we're on,
how to get the next question, how to check the answer.
And as long as it's able to do that and perform the functionality of a quiz,
it's unconcerned by where the data comes from, how it's formatted, and it will continue to work.
복습 후
다음 퀴즈프로젝트는 직접 class, attribution, method를 만들어서 object로 실행하는 것까지를 실습하는 수업이었다.
어떤걸 Attribution으로 만들어주는건지. 어떤걸 Method로 만들어주는건지..?
Method는 차라리 쉬울 것 같은데 def문 같은걸 Method로 만들어준다고 생각하면
Attribution이 잘 감이 안잡힌다. 아마 변수를 미리 선언해주는걸 attribution에 작성해주는 것 같다.
그러니까 미리 선언해주는 변수 같은게 attribution이고 def문이 method로 좀 더 구조화되는 느낌인 것 같다
아 예전부터 궁금하던거 왜 어떤건 뒤에 ()를 작성해주고, 어떤건 ()없이 작성이 되는건지 궁금했는데
클래스의 attribution값을 불러올때는 ()없이 쓰는거고
클래스의 method를 실행시킬 때는 ()와 함께 작성하는 거였구나..!
'Python > [Udemy] 100개의 프로젝트로 Python 개발 완전 정복' 카테고리의 다른 글
Day19 | 중급 | 인스턴스, 상태 및 고차함수 (0) | 2024.01.03 |
---|---|
Day 18 | 중급 | 터틀 & 그래픽 사용자 인터페이스 (GUI) (2) | 2024.01.02 |
Day16 | 중급 | 객체 지향 프로그래밍(OOP) (0) | 2023.12.27 |
Day15 | 중급 | 커피 머신 프로젝트 (0) | 2023.12.26 |
Day12 | 초급 | 유효 범위와 숫자 맞추기 게임 복습 (0) | 2023.12.20 |