Python Encapsulation
What is Encapsulation?
Encapsulation is an Object-Oriented Programming (OOP) principle used to restrict direct access to some of an object's components and bundle data and methods that operate on the data.
It helps:
- Prevent unintended interference.
- Protect internal object states.
- Create a clear structure for code maintenance.
How is Encapsulation Done in Python?
Python uses access modifiers to implement encapsulation:
Modifier | Syntax | Access Level |
---|---|---|
Public | name | Accessible anywhere |
Protected | _name | Accessible within class and subclasses |
Private | __name | Accessible only within the class (name mangling) |
Example 1: Public Members
class Person:
def __init__(self, name):
self.name = name # public attribute
p = Person("Simran")
print(p.name) # Accessible
Output:
Simran
Example 2: Protected Members
class Person:
def __init__(self, name):
self._name = name # protected attribute
class Student(Person):
def show(self):
print("Name:", self._name)
s = Student("Dharmendra")
s.show()
Output:
Name: Dharmendra
Explanation:
_name
is protected; it's a convention, not enforced by Python. It can be accessed but shouldn't be from outside.
Example 3: Private Members
class Account:
def __init__(self, balance):
self.__balance = balance # private attribute
def show_balance(self):
print("Balance:", self.__balance)
a = Account(1000)
a.show_balance()
Output:
Balance: 1000
Direct Access to Private Members
print(a.__balance)
Output:
AttributeError: 'Account' object has no attribute '__balance'
Accessing Private Members (Not Recommended)
print(a._Account__balance)
Output:
1000
Warning:
This uses name mangling, and although possible, it breaks encapsulation.
Example 4: Encapsulation with Setters and Getters
class Product:
def __init__(self):
self.__price = 0
def set_price(self, price):
if price > 0:
self.__price = price
else:
print("Invalid price")
def get_price(self):
return self.__price
p = Product()
p.set_price(500)
print("Price:", p.get_price())
Output:
Price: 500
Key Benefits of Encapsulation
- Data hiding
- Better control of class behavior
- Increased security
- Code modularity