Advanced Python: OOP (Advanced)

Goal

Step 1: Inheritance


class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def bark(self):
        print(self.name + " barks!")

dog = Dog("Bello")
dog.bark()  # Output: Bello barks!

Explanation:

Step 2: Create Quiz Classes


# Question class
class Question:
    def __init__(self, text, answer):
        self.text = text
        self.answer = answer

# Player class
class Player:
    def __init__(self, name):
        self.name = name
        self.score = 0

# Quiz class
class Quiz:
    def __init__(self, questions):
        self.questions = questions

    def start(self, player):
        for question in self.questions:
            guess = input(question.text + " ").lower()
            if guess == question.answer.lower():
                print("Correct!")
                player.score += 1
            else:
                print("Wrong!")
        print(f"{player.name} scored {player.score} out of {len(self.questions)} points!")

Step 3: Start the Quiz


# Create questions
questions = [
    Question("Capital of Germany?", "Berlin"),
    Question("2+2 = ?", "4"),
    Question("Is Python a programming language?", "Yes")
]

# Create player
player = Player("Max")

# Start quiz
quiz = Quiz(questions)
quiz.start(player)

Explanation:

Task