0
0
Pythonprogramming~20 mins

__init__ method behavior in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Init Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
AHonda 2022\nHonda 2022
BToyota 2020\nToyota 2020
CError: missing required positional arguments
DToyota 2020\nHonda 2022
Attempts:
2 left
💡 Hint
Check how default values work in __init__ parameters.
Predict Output
intermediate
2: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')
ANo error, object created successfully
BNameError: name 'name' is not defined
CTypeError: __init__() takes 1 positional argument but 2 were given
DAttributeError: 'str' object has no attribute 'name'
Attempts:
2 left
💡 Hint
Remember that the first parameter of __init__ must be self.
🔧 Debug
advanced
2: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)
A1 1 0
BAttributeError: 'Counter' object has no attribute 'count'
C1 2 2
D0 0 0
Attempts:
2 left
💡 Hint
Consider how `self.count += 1` resolves `self.count` on the right-hand side.
Predict Output
advanced
2: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()
ANo output, object created silently
BTypeError: __init__ should return None, not 'int'
CInit called
D5
Attempts:
2 left
💡 Hint
Check what Python expects __init__ to return.
🧠 Conceptual
expert
3: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?
A['apple'] because both b1 and b2 share the same default list
B[] because each instance has its own list
CError: cannot append to default argument
D['apple'] only in b1, b2.items is []
Attempts:
2 left
💡 Hint
Default arguments are evaluated once when the function is defined.