B Encapsulation & Access Control
Q12.Define encapsulation.
Encapsulation is an OOP concept in which we bundle data (variables) and methods (functions) into a single unit (class) and restrict direct access to the data.
Q13.Does Python have strict “private” or “protected” keywords?
No. Unlike Java or C++, Python does not have strict private or protected keywords; it relies on naming conventions to signal how data should be accessed.
Q14.Why is encapsulation important?
It protects data from unwanted access, improves security, makes code easier to manage, and allows controlled modification.
Q15.Give a real-life example of encapsulation.
A bank account — the balance is hidden and can only be accessed using methods like deposit() and withdraw(); you cannot directly change the balance.
Q16.What are the levels of access control in Python?
Public members, Protected members and Private members.
Q17.What are public members?
Members accessible from anywhere — inside or outside the class. By default, all members in Python are public. Syntax: self.attribute_name.
Q18.What are protected members?
Members intended for internal use within the class and its subclasses. It is a convention (not a restriction) that they should not be accessed from outside. Syntax: self._attribute_name (single underscore).
Q19.What are private members?
Highly restricted members that cannot be easily accessed from outside the class. Syntax: self.__attribute_name (double underscore).
Q20.What is name mangling?
Name mangling is a mechanism Python uses to change the internal name of a private variable to prevent accidental access.
Q21.In the BankAccount example, what is the output of print(account.get_balance())?
1200 — starting 1000, deposit 500, withdraw 300 → 1000 + 500 − 300 = 1200.
Q22.Why does print(account.__balance) give an error?
Because __balance is a private variable, so direct access from outside the class is not allowed.
Remember: single underscore _name → protected · double underscore __name → private · no underscore name → public.