Bird
Raised Fist0
Pythonprogramming~20 mins

Object initialization flow 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
🎖️
Object Initialization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of __init__ and __post_init__ in dataclasses

What is the output of this Python code using dataclasses?

Python
from dataclasses import dataclass, field

@dataclass
class Person:
    name: str
    age: int = field(default=0)

    def __post_init__(self):
        print(f"Post init: {self.name} is {self.age} years old")

p = Person("Alice", 30)
print(f"Name: {p.name}, Age: {p.age}")
A
Name: Alice, Age: 30
Post init: Alice is 30 years old
B
Name: Alice, Age: 0
Post init: Alice is 30 years old
C
Post init: Alice is 0 years old
Name: Alice, Age: 30
D
Post init: Alice is 30 years old
Name: Alice, Age: 30
Attempts:
2 left
💡 Hint

Remember that __post_init__ runs automatically after __init__ in dataclasses.

Predict Output
intermediate
2:00remaining
Order of __new__ and __init__ methods

What will be printed when this code runs?

Python
class MyClass:
    def __new__(cls):
        print("Creating instance")
        return super().__new__(cls)

    def __init__(self):
        print("Initializing instance")

obj = MyClass()
ACreating instance
B
Creating instance
Initializing instance
C
Initializing instance
Creating instance
DInitializing instance
Attempts:
2 left
💡 Hint

Think about which method runs first when creating an object.

Predict Output
advanced
2:00remaining
Effect of returning a different object in __new__

What is the output of this code?

Python
class A:
    def __new__(cls):
        print("A.__new__ called")
        return super().__new__(cls)

    def __init__(self):
        print("A.__init__ called")

class B(A):
    def __new__(cls):
        print("B.__new__ called")
        return "Not an instance"

    def __init__(self):
        print("B.__init__ called")

obj = B()
print(type(obj))
A
B.__new__ called
<class 'str'>
B
B.__new__ called
B.__init__ called
<class '__main__.B'>
C
A.__new__ called
A.__init__ called
<class '__main__.B'>
D
B.__new__ called
A.__init__ called
<class '__main__.B'>
Attempts:
2 left
💡 Hint

What happens if __new__ returns something that is not an instance of the class?

🧠 Conceptual
advanced
2:00remaining
Understanding attribute initialization order

Consider this class:

class C:
    def __init__(self):
        self.x = 10
        self.setup()

    def setup(self):
        self.x = 20

class D(C):
    def setup(self):
        self.x = 30

obj = D()
print(obj.x)

What is the output?

A20
B10
C30
DAttributeError
Attempts:
2 left
💡 Hint

Which setup method runs when obj = D() is created?

🔧 Debug
expert
2:00remaining
Why does this object initialization fail?

What error does this code raise and why?

class E:
    def __init__(self, value):
        self.value = value

class F(E):
    def __init__(self):
        print("Initializing F")

obj = F(5)
ATypeError: F.__init__() takes 1 positional argument but 2 were given
BAttributeError: 'F' object has no attribute 'value'
CSyntaxError: missing colon in class definition
DNo error, prints 'Initializing F'
Attempts:
2 left
💡 Hint

Check the parameters expected by F.__init__ versus what is passed.

Practice

(1/5)
1. What is the purpose of the __init__ method in a Python class?
easy
A. To delete an object when it is no longer needed
B. To define a class-level variable
C. To initialize a new object when it is created
D. To print the object details

Solution

  1. Step 1: Understand the role of __init__

    The __init__ method runs automatically when a new object is created from a class.
  2. Step 2: Identify what __init__ does

    It sets up the initial state of the object by assigning values to its attributes.
  3. Final Answer:

    To initialize a new object when it is created -> Option C
  4. Quick Check:

    __init__ initializes objects [OK]
Hint: Remember: __init__ sets up new objects automatically [OK]
Common Mistakes:
  • Confusing __init__ with __del__
  • Thinking __init__ is for printing
  • Believing __init__ defines class variables
2. Which of the following is the correct syntax to define an __init__ method that takes a parameter name in a Python class?
easy
A. def __init__(self, name):
B. def __init__(name):
C. def init(self, name):
D. def __init__(self):

Solution

  1. Step 1: Recall __init__ method signature

    The first parameter must be self to refer to the new object.
  2. Step 2: Check parameter list

    To accept a name argument, it must be added after self.
  3. Final Answer:

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

    First param is self, then others [OK]
Hint: Always put self first in method parameters [OK]
Common Mistakes:
  • Omitting self parameter
  • Using init instead of __init__
  • Missing parameters after self
3. What will be the output of this code?
class Car:
    def __init__(self, brand):
        self.brand = brand

my_car = Car('Toyota')
print(my_car.brand)
medium
A. Car
B. Toyota
C. brand
D. Error

Solution

  1. Step 1: Understand object creation

    Creating my_car = Car('Toyota') calls __init__ with 'Toyota' as brand.
  2. Step 2: Check attribute assignment and print

    The brand attribute of my_car is set to 'Toyota', so printing my_car.brand outputs 'Toyota'.
  3. Final Answer:

    Toyota -> Option B
  4. Quick Check:

    Attribute value prints 'Toyota' [OK]
Hint: Print attribute after init to see assigned value [OK]
Common Mistakes:
  • Expecting class name instead of attribute value
  • Confusing attribute name with value
  • Thinking print causes error
4. What is wrong with this class definition?
class Person:
    def __init__(self, age):
        age = age

p = Person(30)
print(p.age)
medium
A. The attribute age is not assigned to self
B. The __init__ method is missing self parameter
C. The print statement syntax is incorrect
D. The class name should be lowercase

Solution

  1. Step 1: Check attribute assignment inside __init__

    The code assigns age = age, which only reassigns the local variable, not the object's attribute.
  2. Step 2: Understand how to assign attributes

    To store the value in the object, it should be self.age = age.
  3. Final Answer:

    The attribute age is not assigned to self -> Option A
  4. Quick Check:

    Use self.attribute = value to save data [OK]
Hint: Always assign attributes with self.attribute = value [OK]
Common Mistakes:
  • Forgetting self in attribute assignment
  • Thinking local variable sets object attribute
  • Ignoring error messages about missing attributes
5. Given this class:
class Book:
    def __init__(self, title, author='Unknown'):
        self.title = title
        self.author = author

b1 = Book('Python 101')
b2 = Book('Learn AI', 'Alice')

What are the values of b1.author and b2.author?
hard
A. Both b1.author and b2.author are 'Unknown'
B. b1.author is 'Python 101', b2.author is 'Learn AI'
C. b1.author is None, b2.author is 'Alice'
D. b1.author is 'Unknown', b2.author is 'Alice'

Solution

  1. Step 1: Understand default parameter usage

    The author parameter has a default value 'Unknown', used if no argument is given.
  2. Step 2: Check object creation

    b1 is created with only title, so author defaults to 'Unknown'. b2 provides 'Alice' explicitly.
  3. Final Answer:

    b1.author is 'Unknown', b2.author is 'Alice' -> Option D
  4. Quick Check:

    Default params fill missing arguments [OK]
Hint: Default values apply when argument is missing [OK]
Common Mistakes:
  • Assuming missing argument becomes None
  • Mixing title and author values
  • Forgetting default parameter behavior