Object-Oriented Programming Basics
Python is an object-oriented programming (OOP) language, meaning the focus of the code is on the objects or datasets, rather than on the functions themselves.
The four main elements of OOPs are encapsulation, abstraction, inheritance, and polymorphism. Object-oriented programming was designed to simplify the code development process, minimizing the need to copy and paste code.
Encapsulation
Encapsulation is when a group of similar variables and functions are combined into one object, by defining them in a group like a class. Encapsulation helps protect and secure data and prevents code from being altered by others. To make a given element private in Python, add an underscore before it in the code, like this:
_private,
Or, to perform name mangling, add a double underscore before an attribute, like this:
__private.
Encapsulation makes code more efficient by eliminating the need for lengthy parameters attached to functions. And it allows you to reuse objects in different places and programs.
Abstraction
Abstraction is when you are able to block off certain functions and methods from the rest of the code. Abstraction is helpful in coding because it:
- Reduces the number of functions and methods needed
- Simplifies the code • Minimizes the effects of changes
Inheritance
Inheritance is the principle of object-oriented programming that represents the streamlined, simple nature of the language. It helps to reduce redundancy by applying a set of properties and methods to multiple objects. Rather than having to repeat those properties and methods every time, they can inherit the information, reducing the overall amount of code.
Polymorphism
Polymorphism gives OOPs flexibility — rather than applying a method in the same way to each element or object, methods are applied to individual objects and can be run in different ways based on the type of object.
This replaces more complex code called a switch-case statement in other programming languages. In Python, you can write one line of code with a method added on to achieve the same result.
Click below to reveal the pros and cons of OOPS versus Functional Programming.