Challenge - 5 Problems
Constructor Default Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of constructor with default values
What is the output of this Python code when creating an object without passing any arguments?
Python
class Car: def __init__(self, color='red', speed=0): self.color = color self.speed = speed car = Car() print(car.color, car.speed)
Attempts:
2 left
💡 Hint
Look at the default values set in the constructor parameters.
✗ Incorrect
The constructor sets default values for color as 'red' and speed as 0. Since no arguments are passed, these defaults are used.
❓ Predict Output
intermediate2:00remaining
Constructor default values with partial arguments
What will be printed when creating an object with one argument, leaving the other to default?
Python
class Book: def __init__(self, title='Unknown', pages=100): self.title = title self.pages = pages book = Book('Python 101') print(book.title, book.pages)
Attempts:
2 left
💡 Hint
Only the first parameter is given, the second uses its default.
✗ Incorrect
The title is set to 'Python 101' from the argument, pages uses the default 100.
❓ Predict Output
advanced2:00remaining
Effect of mutable default argument in constructor
What is the output of this code after creating two objects and modifying one object's list?
Python
class Basket: def __init__(self, items=[]): self.items = items basket1 = Basket() basket2 = Basket() basket1.items.append('apple') print(basket2.items)
Attempts:
2 left
💡 Hint
Think about what happens when a mutable default argument is shared.
✗ Incorrect
The default list is shared between instances, so modifying basket1's items affects basket2's items.
❓ Predict Output
advanced2:00remaining
Correct way to avoid mutable default argument issue
What will be printed after creating two objects and modifying one object's list with this constructor?
Python
class Basket: def __init__(self, items=None): if items is None: items = [] self.items = items basket1 = Basket() basket2 = Basket() basket1.items.append('apple') print(basket2.items)
Attempts:
2 left
💡 Hint
Check how the list is created inside the constructor.
✗ Incorrect
Each object gets its own list because a new list is created inside the constructor if no argument is given.
🧠 Conceptual
expert2:00remaining
Why avoid mutable default arguments in constructors?
Why is it recommended to avoid using mutable objects like lists or dictionaries as default values in constructor parameters?
Attempts:
2 left
💡 Hint
Think about what happens when you change a mutable default argument in one object.
✗ Incorrect
Mutable default arguments are created once when the function is defined, so all instances share the same object, leading to shared state bugs.