- LPU MCA Semester 1
- CAB106
- Unit 3
CAB106 · Unit 3: Encapsulation, inheritance and polymorphism
Encapsulation, data hiding and access specifiers
11 practice questions
Key points
- Encapsulation bundles data with methods and controls access
- _x is convention; __x is renamed to _Class__x
- Outside code reading __x gets AttributeError
- Mangling gives each class its own private name
Encapsulation bundles data and the methods that act on it in one class and controls how the data is reached. Python has no public, protected or private keywords; it uses naming conventions.
| Style | Meaning | Enforced? |
|---|---|---|
name | Public | No restriction |
_name | Protected, for internal use | Convention only |
__name | Private through name mangling | Renamed, not locked |
A name that starts with two underscores and does not end with two is rewritten inside the class to _ClassName__name. So self.__x in class A is stored as _A__x; reading a.__x from outside raises AttributeError, while a._A__x still works. Because the class name is part of the stored name, a subclass assigning self.__v creates a separate _B__v and does not overwrite the parent's _A__v. Mangling also applies to class attributes.
Encapsulation lets a class protect its rules, such as refusing a withdrawal larger than the balance, by offering methods instead of raw attribute access.
Exam trap: double underscores hide the name, not the data. Python privacy is a convention backed by renaming, so it can always be bypassed.
Try two questions
What does a single leading underscore, as in _rate, tell other programmers?
- The attribute is meant for internal use, but Python does not enforce it
- The attribute is private and Python blocks every outside access to it
- The attribute is a constant whose value Python refuses to change
- The attribute belongs to the class and cannot exist on an object
Show the answer
A. A single underscore is a naming convention for protected or internal members.
Why not B: Only the double-underscore form triggers name mangling, and even that can be bypassed.
Why not C: Python has no constants, and the underscore does not freeze a value.
Why not D: The underscore says nothing about whether the attribute belongs to the class or the object.
Why can code still reach a double-underscore attribute from outside the class?
- Python copies every private attribute into a public dictionary at run time
- Python disables the mangling whenever a program is run from the command line
- Name mangling only renames the attribute, so the mangled name can still be used
- Python gives any module that imports the class a special permission to read it
Show the answer
C. Python enforces privacy by convention and renaming, not by access control.
Why not A: Python makes no such copy.
Why not B: Mangling is done when the class body is compiled and does not depend on how the program starts.
Why not D: Python has no permission system for attributes.