Bird
0
0

Which of the following is the correct way to define a private attribute using name mangling in a Python class?

easy📝 Syntax Q12 of 15
Python - Encapsulation and Data Protection
Which of the following is the correct way to define a private attribute using name mangling in a Python class?
Aself.__my_attr = 5
Bdef __my_attr(self): pass
Cself._my_attr = 5
Dself.my_attr__ = 5
Step-by-Step Solution
Solution:
  1. Step 1: Identify private attribute syntax

    Private attributes use double underscores at the start of the name, like __my_attr.
  2. Step 2: Check correct assignment

    Assigning with self.__my_attr = 5 correctly defines a private attribute with name mangling.
  3. Final Answer:

    self.__my_attr = 5 -> Option A
  4. Quick Check:

    Double underscore prefix = private attribute [OK]
Quick Trick: Use double underscores before attribute name for private [OK]
Common Mistakes:
  • Using single underscore instead of double
  • Placing underscores after attribute name
  • Defining private attribute as a method incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes