Encapsulation is one of the fundamental concepts of Object-Oriented Programming (OOP). It refers to the process of wrapping data (variables) and methods (functions) into a single unit, i.e., a class.
It also involves restricting direct access to some data, which helps in protecting the integrity of the data.
Encapsulation is:
The process of binding data and methods together and controlling access to data.
Python provides access specifiers to control access to variables:
| Type | Syntax | Access Level |
|---|---|---|
| Public | name |
Accessible everywhere |
| Protected | _name |
Accessible within class and subclasses |
| Private | __name |
Accessible only within the class |
class Student:
def __init__(self, name):
self.name = name # public
s = Student("Rahul")
print(s.name)
class Student:
def __init__(self, name):
self._name = name # protected
class Student:
def __init__(self, name):
self.__name = name # private
s = Student("Rahul")
# print(s.__name) # Error
Private variables can be accessed using name mangling:
print(s._Student__name)
Encapsulation is often implemented using getter and setter methods.
class Student:
def __init__(self):
self.__marks = 0
def set_marks(self, marks):
self.__marks = marks
def get_marks(self):
return self.__marks
s = Student()
s.set_marks(85)
print(s.get_marks())
Output
85
@property DecoratorPython provides a cleaner way using properties.
class Student:
def __init__(self):
self.__marks = 0
@property
def marks(self):
return self.__marks
@marks.setter
def marks(self, value):
self.__marks = value
s = Student()
s.marks = 90
print(s.marks)
Bank Account
deposit() and withdraw()