Encapsulation:
The term of encapsulation is a fundamental concept of object-oriented programming language. It describes the idea of wrapping data and method in a single unit.
This restricts the accessing of variables and methods directly by using the access specifier (private, protected ,public), it prevents unwanted modification of data.
Python does not have a private keyword but it can happen in Encapsulation.
We have to use single underscore(_) and double underscore(__) prefix the method to makes method private and protected
Program
class A: def __init__(self): self.abc=123 self._abc1=123 self.__abc2=123 obj=A() print(obj.abc) print(obj._abc1) print(obj.__abc2)
Output
123 123 Traceback (most recent call last): File "main.py", line 9, inprint(obj.__abc2) AttributeError: 'A' object has no attribute '__abc2'
Above program error “‘ A’ object has no attribute ‘__abc2’ “is thrown because private variable ‘abc2’ is not accessible from outside of class a and is not shown to outside . (single underscore for protected and double underscore for private declaration).
If we want to access the ‘abc2’ variable so we should give the reference of class A to access a ‘abc2’ variable.
Program(rectify)
class A: def __init__(self): self.abc=123 self._abc1=123 self.__abc2=123 obj=A() print(obj.abc) print(obj._abc1) print(obj._A__abc2) #given the reference of class for accessing class A members
Output
123 123 123