Bird
Raised Fist0
Pythonprogramming~20 mins

__init__ method behavior in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1.

What is the main purpose of the __init__ method in a Python class?

easy
A. To create a new class
B. To delete an object from memory
C. To print information about the class
D. To set up initial values for the object's attributes

Solution

  1. Step 1: Understand the role of __init__

    The __init__ method runs automatically when an object is created to set up initial values.
  2. Step 2: Compare options with this role

    Only To set up initial values for the object's attributes describes setting initial attribute values, which matches __init__'s purpose.
  3. Final Answer:

    To set up initial values for the object's attributes -> Option D
  4. Quick Check:

    __init__ sets initial values = A [OK]
Hint: Remember: __init__ sets starting info for objects [OK]
Common Mistakes:
  • Thinking __init__ deletes objects
  • Confusing __init__ with printing methods
  • Believing __init__ creates classes
2.

Which of the following is the correct way to define an __init__ method inside a Python class?

class Car:
    ?
easy
A. def __init__(self, model):
B. def init(self, model):
C. def __start__(self, model):
D. def __init__(model):

Solution

  1. Step 1: Check method name and parameters

    The method must be named exactly __init__ and include self as the first parameter.
  2. Step 2: Compare options

    Only def __init__(self, model): uses the correct name and includes self properly.
  3. Final Answer:

    def __init__(self, model): -> Option A
  4. Quick Check:

    Correct __init__ syntax = D [OK]
Hint: Always include self as first parameter in __init__ [OK]
Common Mistakes:
  • Omitting self parameter
  • Misspelling __init__ method name
  • Using wrong method names like init or __start__
3.

What will be the output of this code?

class Dog:
    def __init__(self, name):
        self.name = name

my_dog = Dog("Buddy")
print(my_dog.name)
medium
A. Buddy
B. name
C. Dog
D. Error

Solution

  1. Step 1: Understand object creation and attribute assignment

    The __init__ method sets self.name to "Buddy" when my_dog is created.
  2. Step 2: Check the print statement

    Printing my_dog.name outputs the string "Buddy" stored in the attribute.
  3. Final Answer:

    Buddy -> Option A
  4. Quick Check:

    Object attribute value = Buddy [OK]
Hint: Print object.attribute to see stored value from __init__ [OK]
Common Mistakes:
  • Printing class name instead of attribute
  • Expecting attribute name instead of value
  • Assuming code causes error
4.

Find the error in this class definition:

class Person:
    def __init__(name):
        self.name = name

p = Person("Alice")
medium
A. Wrong class name
B. Missing self parameter in __init__
C. Missing parentheses when creating object
D. No error

Solution

  1. Step 1: Check __init__ method parameters

    The __init__ method must have self as the first parameter, but it is missing here.
  2. Step 2: Identify impact of missing self

    Without self, self.name causes an error because self is undefined.
  3. Final Answer:

    Missing self parameter in __init__ -> Option B
  4. Quick Check:

    __init__ needs self first [OK]
Hint: Always put self as first __init__ parameter [OK]
Common Mistakes:
  • Forgetting self in method parameters
  • Thinking class name must change
  • Missing parentheses when creating object
5.

Consider this class:

class Book:
    def __init__(self, title, author="Unknown"):
        self.title = title
        self.author = author

b1 = Book("Python 101")
b2 = Book("Learn AI", "Dr. Smith")
print(b1.author, b2.author)

What will be printed?

hard
A. Dr. Smith Unknown
B. Python 101 Learn AI
C. Unknown Dr. Smith
D. Error due to missing author argument

Solution

  1. Step 1: Understand default parameter in __init__

    The author parameter has a default value "Unknown", so it is optional when creating an object.
  2. Step 2: Analyze object creations

    b1 is created with only title, so author is "Unknown". b2 provides both title and author "Dr. Smith".
  3. Step 3: Check print output

    Printing b1.author and b2.author prints "Unknown Dr. Smith".
  4. Final Answer:

    Unknown Dr. Smith -> Option C
  5. Quick Check:

    Default parameters fill missing values = A [OK]
Hint: Default values fill missing arguments in __init__ [OK]
Common Mistakes:
  • Expecting error when argument is missing
  • Mixing up title and author values
  • Assuming both arguments are always required