Recall & Review
beginner
What is a constructor in Python classes?
A constructor is a special method named
__init__ that runs when you create a new object from a class. It sets up the object’s initial state.Click to reveal answer
beginner
How do you set a default value for a constructor parameter in Python?
You assign a value to the parameter in the
__init__ method like def __init__(self, name='Guest'):. If no argument is given, the default is used.Click to reveal answer
beginner
Why use default values in constructors?
Default values let you create objects without giving all details every time. This makes your code simpler and more flexible.Click to reveal answer
beginner
What happens if you call a constructor without a parameter that has a default value?
The constructor uses the default value for that parameter automatically.
Click to reveal answer
beginner
Show a simple example of a Python class with a constructor that has a default value.Example:<br><pre>class Person:
def __init__(self, name='Guest'):
self.name = name
p1 = Person()
print(p1.name) # Output: Guest
p2 = Person('Alice')
print(p2.name) # Output: Alice</pre>Click to reveal answer
What is the purpose of a default value in a constructor parameter?
✗ Incorrect
Default values provide a fallback value when no argument is given during object creation.
How do you define a default value for a parameter in Python's
__init__ method?✗ Incorrect
You assign the default value directly in the parameter list.
What will
print(p.name) output if p = Person() and def __init__(self, name='Guest')?✗ Incorrect
Since no name is passed, the default 'Guest' is used.
Can you have multiple parameters with default values in a constructor?
✗ Incorrect
You can assign default values to as many parameters as you want.
What happens if you call
Person('Bob') when def __init__(self, name='Guest')?✗ Incorrect
The passed argument overrides the default value.
Explain how default values in constructors help when creating objects.
Think about what happens if you don't pass some values when making an object.
You got /4 concepts.
Write a simple Python class with a constructor that has two parameters, one with a default value.
Use <code>def __init__(self, param1, param2=default):</code> format.
You got /4 concepts.