Bird
0
0

How do you correctly declare a protected attribute named _level inside a Python class?

easy📝 Syntax Q3 of 15
Python - Encapsulation and Data Protection
How do you correctly declare a protected attribute named _level inside a Python class?
Adef __init__(self): self.level = 0
Bdef __init__(self): self._level = 0
Cdef __init__(self): self.__level = 0
Ddef __init__(self): _level = 0
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute declaration

    Attributes are usually declared inside the constructor using self.
  2. Step 2: Protected attribute naming

    Protected attributes use a single underscore prefix, e.g., self._level.
  3. Step 3: Analyze options

    def __init__(self): self._level = 0 correctly assigns self._level = 0 inside __init__. def __init__(self): self.level = 0 lacks underscore, C uses double underscore (private), D assigns to a local variable.
  4. Final Answer:

    def __init__(self): self._level = 0 -> Option B
  5. Quick Check:

    Use self._name for protected attributes [OK]
Quick Trick: Use self._name inside __init__ for protected attributes [OK]
Common Mistakes:
  • Using double underscore for protected instead of private
  • Assigning attribute without self prefix
  • Omitting the underscore prefix

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes