top of page

OOP

  • Writer: 라임 샹큼
    라임 샹큼
  • Mar 10
  • 1 min read

OOP is object oriented programming and the principle itself is quite simple. You assign a class and create attributes and methods. However when this was implemented in real coding, I found it hard to unravel. It was confusing connecting attributes made in the class to methods in the class. It seemed that attributes and methods used the same variables and this made little sense as usually a function can only limit variable use within a function.


class QuizBrain:


def __init__(self, q_list):

self.question_number = 0

self.score = 0

self.question_list = q_list


def still_has_questions(self):

return self.question_number < len(self.question_list)


def next_question(self):

current_question = self.question_list[self.question_number]

self.question_number += 1

user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/False): ")

self.check_answer(user_answer, current_question.answer)


def check_answer(self, user_answer, correct_answer):

if user_answer.lower() == correct_answer.lower():

self.score += 1

print("You got it right!")

else:

print("That's wrong.")

print(f"The correct answer was: {correct_answer}.")

print(f"Your current score is: {self.score}/{self.question_number}")

print("\n")


In this code in the init attributes, attribute question number and score were set at 0 to ensure they started off as such. Question lists were also made as an attribute. Later in the still_has_questions, the method used the attribute names made in the init attribute line.

Also in the next_question method, the current question was made using attributes from the init.


question_bank = []

for question in question_data:

question_text = question["question"]

question_answer = question["correct_answer"]

new_question = Question(question_text, question_answer)

question_bank.append(new_question)


quiz = QuizBrain(question_bank)


while quiz.still_has_questions():

quiz.next_question()


print("You've completed the quiz")

print(f"Your final score was: {quiz.score}/{quiz.question_number}")


I was confused how the rest of the methods were supplied with the needed input. Apparently, you have to mention it beforehand.

The way it is pointed out above is in the form of quiz = QuizBrain(q_list)


Recent Posts

See All
Reading and writing files

I learned how to read write txt files. I learned how to navigate files. I always wondered how people sent automated emails to so many...

 
 
 
Ping-Pong game

This project really helped me understand OOP more and grasp the concept of inheritance in classes. screen = Screen() screen.setup(height...

 
 
 
Making the well-known Snake game

Everyone has atleast had one instance in which they downloaded snake.io on their phone and had a few goes at it. I wanted to replicate...

 
 
 

Comments


© 2024 by GifTED. Powered and secured by Wix

bottom of page