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?

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

All tutorials · Try the free PySpark compiler · Practice challenges