0
0
Pythonprogramming~20 mins

Constructor parameters in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.