Bird
0
0

You want to create a class that stores a user's name and age, but age should default to 18 if not provided. How should you define the constructor?

hard📝 Application Q8 of 15
Python - Constructors and Object Initialization
You want to create a class that stores a user's name and age, but age should default to 18 if not provided. How should you define the constructor?
Adef __init__(self, name, age): if age is None: age = 18
Bdef __init__(self, name, age=18):
Cdef __init__(self, name): self.age = 18
Ddef __init__(self, name, age): self.age = age or 18
Step-by-Step Solution
Solution:
  1. Step 1: Understand default parameter values

    Python allows default values in parameters, so age=18 sets default age.
  2. Step 2: Check constructor definition

    def __init__(self, name, age=18): correctly sets age default and requires name.
  3. Final Answer:

    def __init__(self, name, age=18): -> Option B
  4. Quick Check:

    Default parameter syntax = param=default [OK]
Quick Trick: Use default values in parameters for optional arguments [OK]
Common Mistakes:
  • Setting default inside method body instead of parameter
  • Not handling missing age properly
  • Using incorrect syntax for defaults

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes