Python Encapsulation 🔒
Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.
✨ Protected Members
Protected members (in C++ and JAVA) are those members of the class that cannot be accessed outside the class but can be accessed from within the class and its subclasses. To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore _.
class Base:
def __init__(self):
self._a = 2
class Derived(Base):
def __init__(self):
Base.__init__(self)
print("Calling protected member of base class: ", self._a)
self._a = 3
print("Calling modified protected member outside class: ", self._a)
obj1 = Derived()
obj2 = Base()
print("Accessing protected member of obj1: ", obj1._a)
print("Accessing protected member of obj2: ", obj2._a)🔒 Private Members
Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private instance variables that cannot be accessed except inside an object. However, a convention is being followed where a name prefixed with two underscores __ is treated as a non-public part of the API.
class Base:
def __init__(self):
self.a = "GeeksforGeeks"
self.__c = "GeeksforGeeks"
class Derived(Base):
def __init__(self):
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c) # AttributeError
obj1 = Base()
print(obj1.a)
# print(obj1.__c) # AttributeError💡 Did You Know?
Python performs name mangling of private variables. Every member with a double underscore will be changed to _object._class__variable. So, it can still be accessed from outside the class, but the practice should be refrained.