Python Classes and Objects: Abstraction and Encapsulation

In this Python Classes and Objects article we want to talk about Python Abstraction and Encapsulation, so Python is an object oriented programming language that is designed to work with objects. Objects are instances of classes and classes provide a blueprint for creating objects. one of the key principles of Python object oriented programming is encapsulation, so using Python encapsulation we can hide the internal details of an object from outside world, also another important principle that we have in object oriented programming is Python abstractions, so Python abstraction is used to simplify complex systems by breaking them in to smaller parts.

 

 

 

Abstraction in Python Classes

So we already have talked that abstraction is used to simplify complex systems by breaking them in to smaller parts. in Python classes abstraction can be achieved using abstract methods and abstract classes. abstract method is a method that is declared, but has no implementation. it is up to the subclasses to provide the implementation for the abstract method. abstract class is a class that has one or more abstract methods, and therefore cannot be instantiated on its own.

 

 

This is an example of Abstraction in Python

In the above example Shape is an abstract class that defines abstract method area. Rectangle class is a subclass of Shape, and provides an implementation for the area method. this allows us to create rectangle object and calculate its area without knowing the details of how the area is calculated.

 

 

This will be the result

Python Classes and Objects: Abstraction and Encapsulation
Python Classes and Objects: Abstraction and Encapsulation

 

 

Encapsulation in Python Classes

So we already have talked that using encapsulation we can hide the internal details of an object from outside world. in Python classes encapsulation can be done through the use of private variables and methods. private variable or method is a variable or method that is not intended to be accessed from outside the class. Private variables and methods are indicated by double underscore before their names.

 

 

This is an example of Python Encapsulation

In the above example BankAccount is a class that has private variable __balance. deposit and withdraw methods allows us to manipulate the balance of the account, but balance itself cannot be accessed from outside the class. when we try to access balance using account.__balance we get an AttributeError because the balance is private and cannot be accessed from outside the class.

 

 

This will be the result

Python Encapsulation
Python Encapsulation

 

 

Learn More

Leave a Comment