Python Encapsulation

Table Of Contents:

  1. What Is Encapsulation?
  2. Why We Need Encapsulation?
  3. How To Implement Encapsulation?
  4. Access Modifiers In Python.
  5. Public Members.
  6. Private Members.
  7. Protected Members.

(1) What Is Encapsulation?

  • When you take lunch to school, you generally put it inside the lunch box to protect it from the outside environment.
  • Like this in the programming world, to protect your sensitive information you need encapsulation.
  • Encapsulation allows us to protect our properties and methods of the class from the other classes, which you have not written by yourself.
  • When another method of the class is trying to access your members, then it has to go through a security check.
  • If they pass the security check, then only they can able to access the variables and methods.

(2) Why We Need Encapsulation?

1. Encapsulation provides well-defined, readable code.

  • The primary advantage of using Encapsulation is that as a user, we do not need to know the architecture of the methods and the data and can just focus on making use of these functional, encapsulated units for our applications.
  • This results in a more organized and clean code. The user experience also improves greatly and makes it easier to understand applications as a whole.

2. Prevents Accidental Modification or Deletion

  • Another advantage of encapsulation is that it prevents the accidental modification of the data and methods.
  • Let’s consider the example of Pandas library, if I had access to edit the library, then I might make a mistake in the implementation of the function and then because of that mistake, thousands of projects using Pandas would become inaccurate.

3. Encapsulation provides security

  • Encapsulation in Python is achieved through the access modifiers.
  • These access modifiers ensure that access conditions are not breached and thus provide a great user experience in terms of security.

(3) How To Implement Encapsulation?

  • Encapsulation can be implemented by using access modifiers.
  • Sometimes there might be a need to restrict or limit access to certain variables or functions while programming.
  • That is where access modifiers come into the action.

1. Access Modifiers

  • Access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods, constructors, data members, and the setter methods.
  • Compared to languages like Java that offer access modifiers (public or private) for variables and methods, Python provides access to all the variables and methods globally.
  • Since we do not have access modifiers in Python, we will use a few different methods to control the access of variables within a Python program.

2. Public Access Modifiers

  • As the name suggests, the public modifier allows variables and functions to be accessible from anywhere within the class and from any part of the program.
  • All member variables have the access modifier as public by default.

Example:

class Credentials:
    def __init__(self,userName,password):
        self.userName = userName
        self.password = password
    def details(self):
        print('User Name:',self.userName)
        print('Password:',self.password)

Creating Object Of Credentials:

obj = Credentials('Abhispa','abhi@123')

Accessing Public Data Members:

print('User Name:',obj.userName) 
Output:
User Name: Abhispa

Calling Public Member Function Of The Class :

obj.details()
Output:
User Name: Abhispa
Password: abhi@123

Note:

  • From the above code, you can make out that we declared two variables and two methods of the class Credentials.
  • We were able to access the variables and methods wherever we wanted with ease as the access modifier for them was public, which means they should be accessible everywhere.
  • By default Python implement Public Access Modifiers.

3. Private Access Modifiers

  • The private access modifier allows member methods and variables to be accessed only within the class.
  • To specify a private access modifier for a member, we make use of the double underscore __.

Example:

class Credentials:
    def __init__(self,userName,password):
        self.__userName = userName
        self.__password = password
    def details(self):
        print('User Name:',self.__userName)
        print('Password:',self.__password)

Creating Object Of Credentials:

obj = Credentials('Abhispa','abhi@123')

Accessing Private Data Members:

obj.__userName
Output:
AttributeError                            Traceback (most recent call last)
Input In [31], in <cell line: 1>()
----> 1 obj.__userName

AttributeError: 'Credentials' object has no attribute '__userName'
obj.__password
AttributeError                            Traceback (most recent call last)
Input In [23], in <cell line: 1>()
----> 1 obj.__password

AttributeError: 'Credentials' object has no attribute '__password'

Calling Public Member Function Of The Class :

obj.details()
Output:
User Name: Abhispa
Password: abhi@123

Note:

  • We can see that we have received an AttributeError in the output.
  • Since __userName and __password are the private member and we have tried to access it outside the class, that is why we received the above error.

4. Protected Access Modifiers

  • Protected access modifiers allows the members to be accessed within the class and allow them to be accessed by the sub-classes involved.
  • In Python, we implement a protected member by prefixing with an underscore _ before its name.

Example:

class Employee:
    _name = 'Abhispa'
    _salary = 100000
    _company = 'Praudyog'
class Display(Employee):
    def details(self):
        print('Name:',self._name)
        print('Salary:',self._salary)
        print('Company',self._company)

Creating Object Of Display Class:

obj = Display()

Calling Protected Member Of The Class :

obj.details()
Output:
Name: Abhispa
Salary: 100000
Company Praudyog

Calling Protected Member Outside Of The Class :

print("Name:",obj._name)
print("Age:",obj._salary)
print("Age:",obj._company)
Output:
Name: Abhispa
Salary: 100000
Company Praudyog

Note:

  • We can see that we are able to access the protected members inside the child class.
  • It is just indication to the programmer that, it’s a protected member.
  • Python does not enforce this concept mandatorily.
  • \You can able to access the protected members outside of the class also.

Leave a Reply

Your email address will not be published. Required fields are marked *