Loading

Quipoin Menu

Learn • Practice • Grow

python / Encapsulation
interview

Q1. What is encapsulation in Python?
Encapsulation is the bundling of data and methods within a class, and restricting access to some components. Python achieves encapsulation using naming conventions (single underscore _ for protected, double underscore __ for private) and property decorators.

Q2. How do you create private attributes in Python?
Use double underscore prefix (__). Python name-mangles them to _ClassName__attribute. Example:
class MyClass: def __init__(self): self.__private = 10
This discourages external access, but it's still accessible via mangled name.

Q3. What is the difference between private and protected attributes?
By convention, a single underscore _ indicates protected (should not be accessed outside class, but no name mangling). Double underscore __ indicates private (name mangling for stronger protection). However, both are conventions; Python does not enforce true access restrictions.

Q4. How do you use properties to control attribute access?
Use the @property decorator to define getter, setter, and deleter methods. This allows custom logic when accessing attributes while maintaining a simple interface. Example:
class Person: def __init__(self, name): self._name = name @property def name(self): return self._name @name.setter def name(self, value): self._name = value

Q5. Is encapsulation truly enforced in Python?
No, Python does not enforce strict encapsulation like Java. It relies on naming conventions and name mangling to signal intent. Developers are expected to respect the conventions, but the language allows access to all attributes. It's we are all consenting adults" philosophy.
"