Tutorial 5 : OOPs in Python — Encapsulation-Public, Private attributes

Gaurav Patil
3 min readJan 18, 2022
Photo by Hitesh Choudhary on Unsplash

Missed previous lecture ?? — Click here

In this tutorial we will cover following topics :

Encapsulation

Encapsulation as wrapping of data with methods in class

Encapsulation as access restriction

Name mangling

Encapsulation :

  • wrapping of data with methods operating on that data in class
  • restricting access to the data or methods that can manipulate it

Encapsulation as wrapping of data with methods in class :

Encapsulation as access restriction :

Objects can be -

pubic - accessible and modifiable outside class

private - not easily accessible and modifiable outside class

protected - objects can be accessible but can be made not modifiable outside class

NOTE : private attributes and private methods are preceded by two underscores

As you can see all the public attributes and public method can be accessed and modified outside class.

As you can see now private attribute and methods cannot be accessed outside the class — this is what I meant by access restriction using encapsulation.

NOTE : Accessing the private methods and private attributes outside class fetches AttributeError .

Name mangling :

Name mangling to bypass access restriction for private attributes and methods.

Use object._class__private_variable OR object._class__private_method to access the private attribute and call private method as shown below.

I hope now you have pretty good understanding of encapsulation. We will learn about protected attributes in next tutorial.

Take a deep breathe and move to the next tutorial.

--

--

Gaurav Patil

Machine Learning Engineer drawing insights from mathematics.