Encapsulation
Encapsulation
• For example, imagine a bank account. The balance in your account should only be
changed by specific actions, such as deposits or withdrawals, not directly by
anyone accessing the balance. By encapsulating the balance inside the class and
providing controlled access through methods (deposit, withdraw), you ensure that
the balance cannot be tampered with directly.
Access Modifiers in Python Encapsulation
• We can protect variables in the class by marking them private. To define a private
variable add two underscores as a prefix at the start of a variable name.
• Private members are accessible only within the class, and we can’t access them
directly from the class objects.
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
• _classname__dataMember
• Protected members are accessible within the class and also available to its sub-
classes. To define a protected member, prefix the member name with a single
underscore _.
• Protected data members are used when you implement inheritance and want to
allow data members access to only child classes.
# base class
class Company: def __init__(self):
# Protected member
self._project = "NLP"
# child class
class Employee(Company):
OUTPUT:
def __init__(self, name):
self.name = name Employee name : Jessa
Company.__init__(self)
Working on project : NLP
def show(self):
print("Employee name :", self.name) Project: NLP
# getter methods
def get_roll_no(self):
return self.__roll_no