Encapsulation in Python
Python tutorial · PySpark.in
Encapsulation in Python
Encapsulation is the process of wrapping data (variables) and methods (functions) into a single unit — called a class.
It helps to protect data from being directly accessed or modified from outside the class.
Why Use Encapsulation?
- To protect data from accidental modification.
- To make code secure and organized.
- To give controlled access to class variables using methods.
How Encapsulation Works in Python
Python doesn’t have true “private” variables like some other languages,
but it provides naming conventions to indicate variable visibility:
Type | Syntax | Access |
|---|---|---|
Public | self.var | Accessible anywhere |
Protected | _self.var | Accessible within class & subclasses |
Private | __self.var | Not directly accessible outside class |
Example: Public Members
```
class Student:
def __init__(self, name, roll):
self.name = name # public variable
self.roll = roll
# Creating object
s1 = Student("Megha", 101)
print(s1.name) # Accessible
print(s1.roll) # Accessible
```
Both variables are public, so they can be accessed from anywhere.
Example: Private Members (Data Hiding)
```
class Student:
def __init__(self, name, roll):
self.__name = name # private variable
self.__roll = roll
def display(self):
print(f"Name: {self.__name}, Roll: {self.__roll}")
# Object
s1 = Student("Megha", 101)
# Accessing through method (allowed)
s1.display()
# Accessing directly (not allowed)
print(s1.__name) # Error
```
Direct access to __name or __roll is not allowed — data is hidden.
Example: Using Getter and Setter Methods
Encapsulation is best used with getter and setter methods to safely access or modify private data.
```
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private variable
# Getter method
def get_balance(self):
return self.__balance
# Setter method
def set_balance(self, amount):
if amount > 0:
self.__balance = amount
else:
print("Invalid amount!")
# Object
account = BankAccount(5000)
print("Initial Balance:", account.get_balance())
account.set_balance(8000)
print("Updated Balance:", account.get_balance())
account.set_balance(-100) # Invalid update
```
Here, access to the private variable __balance is controlled by get_balance() and set_balance().
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges