Bird
Raised Fist0
Pythonprogramming~20 mins

Constructor parameters 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
🎖️
Constructor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
AError: missing argument for year
B
Toyota 2020
Honda 2018
C
Toyota 2020
Honda 2020
D
Toyota None
Honda 2018
Attempts:
2 left
💡 Hint
Look at the default value assigned to the year parameter in the constructor.
Predict Output
intermediate
2: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)
AError: *args not allowed in constructor
B[1, 2, 3]
C{1, 2, 3}
D(1, 2, 3)
Attempts:
2 left
💡 Hint
Remember what *args collects in Python functions.
Predict Output
advanced
2: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)
AAlice 30
BAlice None
CError: missing required keyword-only argument 'age'
DError: positional argument after keyword-only argument
Attempts:
2 left
💡 Hint
The * in the parameter list means age must be passed as a keyword argument.
Predict Output
advanced
2: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)
A['apple']
B['apple', 'apple']
C[]
DError: mutable default argument not allowed
Attempts:
2 left
💡 Hint
Think about what happens when you use a list as a default parameter.
Predict Output
expert
2: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')
ACircle with size 5
BSquare with size 5
CUnknown shape
DError: match-case not supported
Attempts:
2 left
💡 Hint
Look at how kwargs are unpacked and how match-case works with strings.

Practice

(1/5)
1. What is the purpose of constructor parameters in a Python class?
easy
A. To provide initial values to an object when it is created
B. To define methods that the class can use
C. To create global variables outside the class
D. To delete an object from memory

Solution

  1. Step 1: Understand what constructor parameters do

    Constructor parameters allow you to pass values to an object when you create it, so it starts with specific data.
  2. Step 2: Compare options with this understanding

    Only To provide initial values to an object when it is created describes this purpose correctly. Other options describe unrelated concepts.
  3. Final Answer:

    To provide initial values to an object when it is created -> Option A
  4. Quick Check:

    Constructor parameters = initial values [OK]
Hint: Constructor parameters set starting values for new objects [OK]
Common Mistakes:
  • Confusing constructor parameters with methods
  • Thinking constructor parameters delete objects
  • Believing constructor parameters create global variables
2. Which of the following is the correct way to define a constructor with parameters in Python?
easy
A. def __start__(self, name):
B. def constructor(name):
C. def init(self):
D. def __init__(self, name):

Solution

  1. Step 1: Recall Python constructor syntax

    Python uses the special method named __init__ with self as the first parameter to define constructors.
  2. Step 2: Check each option

    Only def __init__(self, name): uses the correct method name and includes self and a parameter.
  3. Final Answer:

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

    Constructor method = __init__ with self [OK]
Hint: Constructor method is always named __init__ with self first [OK]
Common Mistakes:
  • Using wrong method names like constructor or init
  • Omitting self parameter
  • Using incorrect special method names
3. What will be the output of this code?
class Dog:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return f"{self.name} says Woof!"

my_dog = Dog("Buddy")
print(my_dog.speak())
medium
A. Buddy says Woof!
B. Woof!
C. Dog says Woof!
D. Error: missing parameter

Solution

  1. Step 1: Understand constructor parameter usage

    The constructor takes a name and assigns it to self.name. The object my_dog is created with name "Buddy".
  2. Step 2: Analyze the speak method output

    The speak method returns a string using self.name, so it returns "Buddy says Woof!".
  3. Final Answer:

    Buddy says Woof! -> Option A
  4. Quick Check:

    Object name used in speak = Buddy says Woof! [OK]
Hint: Constructor sets name; speak uses it to print message [OK]
Common Mistakes:
  • Ignoring the name parameter and expecting just 'Woof!'
  • Confusing class name with instance name
  • Assuming missing parameters cause error here
4. Identify the error in this class definition:
class Car:
    def __init__(color):
        self.color = color

my_car = Car("red")
medium
A. Missing quotes around "red"
B. Missing self parameter in __init__ method
C. Cannot assign to self.color
D. Wrong method name, should be __start__

Solution

  1. Step 1: Check __init__ method parameters

    The first parameter of __init__ must be self to refer to the instance. Here, self is missing.
  2. Step 2: Confirm other parts are correct

    Method name __init__ is correct, assignment to self.color is valid, and "red" is properly quoted.
  3. Final Answer:

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

    __init__ first parameter = self [OK]
Hint: Always include self as first parameter in __init__ [OK]
Common Mistakes:
  • Forgetting self parameter
  • Changing __init__ method name
  • Misunderstanding self usage
5. You want to create a class Book that stores title and author when you create a new book object. Which constructor correctly sets these attributes?
hard
A. def __init__(title, author): self.title = title self.author = author
B. def __init__(self): title = title author = author
C. def __init__(self, title, author): self.title = title self.author = author
D. def __init__(self, title, author): title = self.title author = self.author

Solution

  1. Step 1: Check parameter list and self usage

    The constructor must have self as first parameter, then title and author. def __init__(self, title, author): self.title = title self.author = author has this correct.
  2. Step 2: Verify attribute assignment

    Attributes must be assigned as self.title = title and self.author = author to store values in the object. def __init__(self, title, author): self.title = title self.author = author does this correctly.
  3. Final Answer:

    def __init__(self, title, author): self.title = title self.author = author -> Option C
  4. Quick Check:

    Use self to assign attributes in __init__ [OK]
Hint: Use self.attribute = parameter inside __init__ [OK]
Common Mistakes:
  • Omitting self parameter
  • Assigning parameters to themselves instead of self
  • Reversing assignment order