In Python, Encapsulation is a fundamental concept of object-oriented programming (OOP). It refers to class as collections of data (variables) and methods that operate on that data.
Encapsulation restricts some components of an object from being accessed directly, so that unintended interference and data corruption may be prevented.
Encapsulation is implemented in Python by stopping users from directly accessing certain parts of an object, while giving them the ability to access those areas through other means (methods).
Access can be controlled using different access modifiers:
| Member Type | Syntax | Accessible Inside Class | Accessible in Subclasses | Accessible Outside Class |
|---|---|---|---|---|
| Public | self.var | Yes | Yes | Yes |
| Protected | self._var | Yes | Yes (Recommended inside subclasses only) | Yes (Not recommended) |
| Private | self.__var | Yes | No (Unless using name mangling) | No (Direct access restricted) |
Python uses three levels of access control for class members:
Let's explore each with examples.
Public members can be accessed everywhere, inside the class, outside the class, and inside derived (child) classes.
Let us take an example to demonstrate public members in Python.
Output:
Toyota Corolla Car: Toyota Corolla
Explanation:
Public attributes (brand, model) will also be accessible outside the class. The display() method which is also public can be accessed from other classes.
Protected members are indicated by a single underscore (_variable).
Let us take an example to demonstrate protected members in Python.
Output:
Brand: Tesla, Model: Model S, Engine: Electric Battery: 100 kWh Model S
Explanation:
_model and _engine are protected attributes,_show_details() is a protected method. They can be accessed in subclasses, but it's not recommended to use them directly outside the class.
Private members are indicated by double underscores (__variable).
Let us take an example to demonstrate private members in Python.
Output:
123456789 1000 2000 2000
Explanation:
__balance is a private attribute; direct access is not allowed. We use getter (get_balance()) and setter (set_balance()) methods to control access. Python renames __balance internally as _BankAccount__balance, allowing access via name mangling (but this is bad practice).
Encapsulation hides the internal details and the implementation of the object's attributes by preventing direct access. In Python, encapsulation is applied through public, protected, and private members for class attributes, and controlling access through getters and setters. It improves the security, maintainability and structure of the code because of the convention-based approach in Python.
We request you to subscribe our newsletter for upcoming updates.