Python is a high level general purpose programming language which has a clear/easy learning curve. Python programming language is massively used in various domains like Artificial Intelligence, Data Science, Web Development, Utilities Tools and Scripts and many more
Python is a Programming language, and the default Python we use is written in C programming language which is also referred to as CPython (Python implementation in C). There are various implementation of Python Programming language i.e Jython(in JAVA), Skulpt(in JS) e.t.c
To make everything easy: We refer CPython as Python
Encapsulation is one of the fundamental concepts in OOP. It describes the idea of bundling data and methods that work on that data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
Protected MembersThose members of the class that cannot be accessed outside the class but can be accessed from within the class and its subclasses are called protected members.
In python, protected members are created by prefixing the name of the member by a single underscore “_”.
class A:
def __init__(self):
self._a = 2
class B(A):
def __init__(self):
A.__init__(self)
print("Getting protected member of class A inside Subclass B: ")
print(self._a)
obj1 = B()
Output
Getting protected member of class A inside Subclass B:
2
Private Members
Private members are those members who are similar to protected members, which is not accessible from outside the class as well as from sub-class.
In python, to define a private member prefix the member name with double underscore “__”.
Example
class A:
def __init__(self):
self.__a = 2 # note double underscore
class B(A):
def __init__(self):
A.__init__(self)
print("Getting private member of class A inside Subclass B: ")
print(self.__a)
obj1 = B()
Output
An error occurs:
AttributeError: 'B' object has no attribute '_B__a'
In case of private members we can use _{ClassName}__{PrivateMember}
class A:
def __init__(self):
self.__a = 2 # note double underscore
class B(A):
def __init__(self):
A.__init__(self)
print("Getting private member of class A inside Subclass B: ")
print(self._A__a) # changed code
obj1 = B()
Output:
2
Note: In Python there is no actual data hiding