Bird
Raised Fist0

Which of the following is the correct way to set a default value for the parameter age in a Python class constructor?

easy📝 Syntax Q12 of Q15
Python - Constructors and Object Initialization
Which of the following is the correct way to set a default value for the parameter age in a Python class constructor?
Adef __init__(self, age:30):
Bdef __init__(self, age): age=30
Cdef __init__(self, age): age == 30
Ddef __init__(self, age=30):
Step-by-Step Solution
Solution:
  1. Step 1: Recall Python syntax for default parameters

    Default values are set by assigning a value in the parameter list, like age=30.
  2. Step 2: Check each option

    def __init__(self, age=30): uses correct syntax. def __init__(self, age): age=30 tries to assign inside the method header, which is invalid. def __init__(self, age): age == 30 uses comparison operator instead of assignment. def __init__(self, age:30): uses incorrect type hint syntax.
  3. Final Answer:

    def __init__(self, age=30): -> Option D
  4. Quick Check:

    Default parameter = param=value [OK]
Quick Trick: Default values go in the parameter list with = [OK]
Common Mistakes:
MISTAKES
  • Assigning default inside the method body
  • Using == instead of = for defaults
  • Confusing type hints with default values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes