Challenge - 5 Problems
Init Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of __init__ with default and custom arguments
What is the output of this Python code when creating an object with and without arguments?
Python
class Car: def __init__(self, brand='Toyota', year=2020): self.brand = brand self.year = year car1 = Car() car2 = Car('Honda', 2022) print(car1.brand, car1.year) print(car2.brand, car2.year)
Attempts:
2 left
💡 Hint
Check how default values work in __init__ parameters.
✗ Incorrect
The __init__ method sets default values for brand and year. car1 uses defaults, car2 uses provided values.
❓ Predict Output
intermediate2:00remaining
Effect of missing self in __init__ method
What happens when the __init__ method is defined without the self parameter?
Python
class Person: def __init__(name): name.name = name p = Person('Alice')
Attempts:
2 left
💡 Hint
Remember that the first parameter of __init__ must be self.
✗ Incorrect
The __init__ method is defined with a single parameter `name`. When instantiating `Person('Alice')`, Python passes two arguments to `__init__`: the instance object (implicit `self`) and the string `'Alice'`. This causes `TypeError: __init__() takes 1 positional argument but 2 were given`.
🔧 Debug
advanced2:00remaining
Why does this __init__ method cause unexpected behavior?
Consider this code. What is the output and why?
Python
class Counter: count = 0 def __init__(self): self.count += 1 c1 = Counter() c2 = Counter() print(c1.count, c2.count, Counter.count)
Attempts:
2 left
💡 Hint
Consider how `self.count += 1` resolves `self.count` on the right-hand side.
✗ Incorrect
`self.count += 1` is equivalent to `self.count = self.count + 1`. Reading `self.count` fetches the class attribute `count` (0) since no instance attribute exists yet. It increments to 1 and sets an instance attribute `self.count = 1`. The class attribute `count` remains 0. Both instances have their own `count=1`.
❓ Predict Output
advanced2:00remaining
Output when __init__ returns a value
What happens if __init__ method returns a value explicitly?
Python
class Sample: def __init__(self): print('Init called') return 5 s = Sample()
Attempts:
2 left
💡 Hint
Check what Python expects __init__ to return.
✗ Incorrect
__init__ must return None. Returning any other value causes TypeError.
🧠 Conceptual
expert3:00remaining
Why does modifying a mutable default argument in __init__ cause bugs?
Consider this class:
class Bag:
def __init__(self, items=[]):
self.items = items
def add(self, item):
self.items.append(item)
b1 = Bag()
b2 = Bag()
b1.add('apple')
print(b2.items)
What is the output and why?
Attempts:
2 left
💡 Hint
Default arguments are evaluated once when the function is defined.
✗ Incorrect
The default list is shared across all instances, so adding to b1.items affects b2.items.