Challenge - 5 Problems
Constructor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a class with default constructor parameters
What is the output of this Python code?
Python
class Car: def __init__(self, make, year=2020): self.make = make self.year = year car1 = Car('Toyota') car2 = Car('Honda', 2018) print(car1.make, car1.year) print(car2.make, car2.year)
Attempts:
2 left
💡 Hint
Look at the default value assigned to the year parameter in the constructor.
✗ Incorrect
The constructor has a default value for year=2020. When car1 is created without specifying year, it uses 2020. car2 specifies 2018, so it uses that.
❓ Predict Output
intermediate2:00remaining
Output when using *args in constructor
What will this code print?
Python
class Numbers: def __init__(self, *args): self.nums = args obj = Numbers(1, 2, 3) print(obj.nums)
Attempts:
2 left
💡 Hint
Remember what *args collects in Python functions.
✗ Incorrect
*args collects all extra positional arguments into a tuple. So self.nums is a tuple (1, 2, 3).
❓ Predict Output
advanced2:00remaining
Output of constructor with keyword-only parameters
What is the output of this code?
Python
class Person: def __init__(self, name, *, age): self.name = name self.age = age p = Person('Alice', age=30) print(p.name, p.age)
Attempts:
2 left
💡 Hint
The * in the parameter list means age must be passed as a keyword argument.
✗ Incorrect
The * forces age to be keyword-only. p is created with age=30 as keyword argument, so it works and prints 'Alice 30'.
❓ Predict Output
advanced2:00remaining
Output when constructor parameters are mutable default arguments
What will this code print?
Python
class Bag: def __init__(self, items=None): if items is None: items = [] self.items = items b1 = Bag() b1.items.append('apple') b2 = Bag() print(b2.items)
Attempts:
2 left
💡 Hint
Think about what happens when you use a list as a default parameter.
✗ Incorrect
Using None as the default and creating a new list inside the constructor avoids sharing the list between instances. So b2.items is empty.
❓ Predict Output
expert2:00remaining
Output of constructor with parameter unpacking and match-case
What is the output of this code?
Python
class Shape: def __init__(self, **kwargs): self.type = kwargs.get('type', 'unknown') self.size = kwargs.get('size', 0) s = Shape(type='circle', size=5) match s.type: case 'circle': print(f'Circle with size {s.size}') case 'square': print(f'Square with size {s.size}') case _: print('Unknown shape')
Attempts:
2 left
💡 Hint
Look at how kwargs are unpacked and how match-case works with strings.
✗ Incorrect
The constructor sets type='circle' and size=5. The match-case matches 'circle' and prints accordingly.