Encapsulation is a core principle of object-oriented programming (OOP) in Python. It refers to the bundling of data and methods that operate on that data within a single unit or object. This concept helps in data hiding and restricting access to certain components of an object.
In Python, encapsulation is implemented using private and protected members:
While Python doesn't have strict access modifiers like some other languages, it follows the "we're all consenting adults" philosophy, relying on convention rather than enforcement.
Here's a simple example demonstrating encapsulation in Python:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return True
return False
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
def get_balance(self):
return self.__balance
In this example, the __balance
attribute is private, and can only be accessed or modified through the class methods.
Python uses name mangling for private attributes. When you prefix an attribute with double underscores, Python changes its name internally:
class MyClass:
def __init__(self):
self.__private_var = 42
obj = MyClass()
print(obj._MyClass__private_var) # Outputs: 42
This mechanism doesn't make the attribute truly private but discourages direct access.
Encapsulation is one of the four fundamental OOP concepts, along with Inheritance, Polymorphism, and Abstraction. Understanding these concepts is crucial for mastering Python Classes and Objects.
For more advanced usage of encapsulation, you might want to explore Python Property Decorators and Python Abstract Classes.