Challenge - 5 Problems
Constructor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Python code using a constructor?
Consider this Python class with a constructor. What will be printed when the code runs?
Python
class Dog: def __init__(self, name): self.name = name my_dog = Dog("Buddy") print(my_dog.name)
Attempts:
2 left
💡 Hint
The constructor sets the name attribute when the object is created.
✗ Incorrect
The __init__ method is the constructor. It sets the name attribute to 'Buddy'. So printing my_dog.name outputs 'Buddy'.
🧠 Conceptual
intermediateWhat is the main purpose of a constructor in Python?
Choose the best description of what a constructor does in a Python class.
Attempts:
2 left
💡 Hint
Think about what happens when you create a new object from a class.
✗ Incorrect
A constructor (__init__) runs automatically when a new object is created. It sets up initial values for the object.
❓ Predict Output
advancedWhat will this code print regarding constructor behavior?
Look at this Python code with a constructor and a method. What is the output?
Python
class Car: def __init__(self, brand): self.brand = brand def show_brand(self): print(f"Brand: {self.brand}") car1 = Car("Toyota") car1.show_brand()
Attempts:
2 left
💡 Hint
The constructor sets the brand attribute, which the method prints.
✗ Incorrect
The constructor sets self.brand to 'Toyota'. The show_brand method prints it. So output is 'Brand: Toyota'.
🧠 Conceptual
advancedWhich statement about constructors is true?
Select the true statement about constructors in Python classes.
Attempts:
2 left
💡 Hint
Think about when the __init__ method runs.
✗ Incorrect
The constructor __init__ runs automatically when a new object is created. Its name must be __init__, it does not return a value, and it can have multiple parameters.
❓ Predict Output
expertWhat is the output of this Python code with multiple constructors?
Python does not support multiple constructors by default. What will happen when this code runs?
Python
class Book: def __init__(self, title): self.title = title def __init__(self, title, author): self.title = title self.author = author b = Book("1984") print(b.title)
Attempts:
2 left
💡 Hint
The second __init__ replaces the first one.
✗ Incorrect
In Python, the second __init__ method overwrites the first. So Book expects two arguments. Calling Book("1984") with one argument causes a TypeError.
