Bird
Raised Fist0

Which of the following is the correct way to define a private attribute named age in a Python class?

easy📝 Syntax Q12 of Q15
Python - Encapsulation and Data Protection
Which of the following is the correct way to define a private attribute named age in a Python class?
Aself.___age
Bself.age
Cself._age
Dself.__age
Step-by-Step Solution
Solution:
  1. Step 1: Identify private attribute syntax

    Private attributes start with exactly two underscores, like __age.
  2. Step 2: Check options

    self.__age uses self.__age, which is correct. self.age is public, self._age is protected (single underscore), self.___age has three underscores which is invalid.
  3. Final Answer:

    self.__age -> Option D
  4. Quick Check:

    Private attribute = double underscore [OK]
Quick Trick: Private attribute = double underscore before name [OK]
Common Mistakes:
MISTAKES
  • Using single underscore instead of double
  • Adding too many underscores
  • Forgetting underscores

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes