Python Encapsulation: Bundling and Hiding Data in Classes
Explore encapsulation in Python, a key concept in object-oriented programming that bundles attributes and methods within a class. Learn how encapsulation hides data members and exposes them through methods, ensuring controlled access to object data. Understand Python's approach using naming conventions for access control, similar to access modifiers in languages like C++ and Java.
Python - Encapsulation
Encapsulation bundles attributes and methods within a single unit. It hides data members from outside access and exposes them through methods, preventing direct access to the object data.
Implementing Encapsulation in Python
In C++ and Java, access modifiers (public, protected, private) restrict access to class members. Python uses naming conventions to achieve similar results.
Example 1: Public Access
Instance variables in Python classes are public by default:
Example: Public Access
class Student:
def __init__(self, name="Rajaram", marks=50):
self.name = name
self.marks = marks
s1 = Student()
s2 = Student("Bharat", 25)
print("Name: {} marks: {}".format(s1.name, s1.marks))
print("Name: {} marks: {}".format(s2.name, s2.marks))
Output
Name: Rajaram marks: 50
Name: Bharat marks: 25
Example 2: Private Access
Prefixing a variable name with double underscores makes it private:
Example: Private Access
class Student:
def __init__(self, name="Rajaram", marks=50):
self.__name = name
self.__marks = marks
def studentdata(self):
print("Name: {} marks: {}".format(self.__name, self.__marks))
s1 = Student()
s2 = Student("Bharat", 25)
s1.studentdata()
s2.studentdata()
print("Name: {} marks: {}".format(s1.__name, s2.__marks))
Output
Name: Rajaram marks: 50
Name: Bharat marks: 25
Traceback (most recent call last):
AttributeError: 'Student' object has no attribute '__name'
What is Name Mangling?
Python uses name mangling to access private members. It changes the variable name to object._class__variable
.
Example: Name Mangling
# Access private member using name mangling
print(s1._Student__marks)
Output
50
Python adapts a mature approach to encapsulation by using naming conventions and allowing name mangling for accessing private data when necessary.