Python Encapsulation Concepts
1. Basic Encapsulation
Encapsulation refers to the bundling of data and methods that operate on that data within a single
unit, or class. It restricts direct access to some of the object's components.
class Employee:
def __init__(self, name, age, salary):
# Private attributes
self.__name = name
self.__age = age
self.__salary = salary
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_salary(self):
return self.__salary
def set_salary(self, salary):
if salary < 0:
print("Salary cannot be negative.")
else:
self.__salary = salary
emp = Employee("John", 30, 50000)
print(emp.get_name()) # John
emp.set_salary(55000)
print(emp.get_salary()) # 55000
2. Controlling Access with Getter and Setter Methods
Getters and setters allow controlled access to private attributes. The setter can contain logic to
validate changes.
class Employee:
def __init__(self, name, age, salary):
self.__name = name
self.__age = age
self.__salary = salary
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self, age):
if age > 18:
self.__age = age
else:
print("Age must be greater than 18")
emp = Employee("Jane", 25, 60000)
print(emp.get_age()) # 25
emp.set_age(17) # Age must be greater than 18
3. Data Hiding Example
Encapsulation hides data from direct access, providing controlled access through public methods.
class Account:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
print("Deposit amount must be positive.")
def get_balance(self):
return self.__balance
acc = Account(1000)
acc.deposit(500) # Deposit 500
print(acc.get_balance()) # 1500
4. Controlling Access Example
Using encapsulation, we control access to an object's data, ensuring that only valid operations are
performed.
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number
self.__balance = balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount("12345678", 2000)
acc.deposit(1000) # Deposit 1000
print(acc.get_balance()) # 3000
5. Name Mangling in Encapsulation
Python uses name mangling to make private attributes less accessible by renaming them internally.
class Employee:
def __init__(self, name):
self.__name = name # Private attribute
emp = Employee("Mike")
print(emp._Employee__name) # Access private attribute using name mangling