A Detailed Guide on OOP in Python
|In this Python tutorial, we will discuss Object-Oriented Programming in Python along with various concepts and some examples in detail.
Python supports different paradigms for programming such as imperative, functional, procedural, and object-oriented. Hence, before starting to discuss the depth of OOP, let’s understand some basics of the OOP tutorial.
1. What is OOP and what is its use?
OOP which is also known as Object-Oriented Programming is one of the most popular paradigms for programming. One of the characteristic that makes OOPS famous and easier to understand is that it allows us to think in terms of objects, attributes, behavior, etc, which makes it closer to real-world scenarios.
Many programming languages support object-oriented programming like C++, Java, Python, etc.
Read More: What is OOP as a concept independent of programming languages.
1.1. Benefits of OOP concept
- With the help of the OOP paradigm, complex programs and lengthy programs can become reproducible, easy, and leads to simple structure programs.
- Once the OOP concept is used in the program, it can be reused across the program and in different programs as well.
- OOP has a concept of polymorphism which permits inheriting and overwriting the behavior of parent classes.
- OOP has a concept of class, which stores realted and useful data and this class is easy to debug.
- OOP has a concept of encapsulation which secures the data and protects the data and all vital information from unauthorised changes.
2. Building block(concepts) of OOP
As we mentioned above that OOP involves the building blocks, let’s discuss what are the building blocks of OOP which can be used.
- Class
- Object
- Inheritance
- Encapsulation
- Data Abstraction
- Polymorphism
- Attributes
- Methods
Fields and methods are not regarded as individual concepts as they are part of different components. These are the main blocks of OOP in Python.
This sums up the whole OOP, the blocks may contain several other blocks inside them which we shall discuss individually. For now, let’s discuss each concept one by one.
3. Class in Python
In simple words, class is a blueprint of an object which contains the definition of various methods and variables. A class is defined as a structure that contains different objects.
The blueprint of the class contains various attributes and its behavior that help in describing an object and this makes the class; a logical entity.
For example: if we have to define a class for a teacher, then it should have certain attributes and methods like name, age, department, salary, experience, subject, education, expertise, and some others.
We can use some in-built class of python but for custom work, we generally need to create our own class. Here, we shall discuss the design of our own class.
Syntax: class ClassName: <<Body of Class>>
class Machine: motor = "DC" # attribute inside the class def __init__(self, price, power, brand): # instance attribute self.price = price self.power = power self.brand = brand
We will discuss more about Python classes in future articles.
4. Object in python
We can define an object as an instance of a class. The class only describes the details or the blueprint of the object. The object is the one that takes the memory in the system when it has been instantiated. So one class can be instantiated multiple times(by default) and all instances are objects of that class.
All the real data is present in the objector instance. Every object has certain behaviors and properties linked to it. Objects can be any real-world entity like a machine, a box, a room, a book, a laptop, a TV, a mobile phone, etc.
Let’s create the object of the above class we defined.
Syntax:
object_name = classname(provided parameters)
# object_1 = Machine(price, power, brand)
Let’s take an example to understand the class and object.
class Machine: motor = "DC" # attribute inside the class def __init__(self, price, power, brand): # instance attribute self.price = price self.power = power self.brand = brand # Object instantiation washing_machine = Machine(12000, "50 Watt", "Samsung") air_conditioner = Machine(22000, "130 Watt", "Samsung") # accessing each attribute of class print("First machine: Price", washing_machine.price, "Power consumption", washing_machine.power, "Brand", washing_machine.brand) print("Second machine: Price", air_conditioner.price, "Power consumption", air_conditioner.power, "Brand", air_conditioner.brand)
Output First machine: Price 12000 Power consumption 50 Watt Brand Samsung Second machine: Price 22000 Power consumption 130 Watt Brand Samsung
All the characteristics are defined within the __init__
method of the class machine
.
As the object was initialized, the initializer method is first to run which is responsible to initialize the data and do all the setup initial setup for the object.
To learn more about objects in Python and their different methods, click here.
5. Inheritance in Python
Inheritance can be defined as a way that allows one class to inherit certain characteristics and operations from any other class.
The parent class is that class which permits other class to inherit its attributes and methods.
The child class is that class that inherits the methods and attributes from the parent class.
The unique thing about this concept is that the child can inherit characteristics as well as it can have their individual methods and attributes.
The child class can also override the behavior of the parents if allowed.
These characteristics of the child class will not affect the parent class.
Syntax: class Parent: <<body of parent>> class Child( Parent): <<body of child class>>
Let’s understand it with a short example.
class Machine: # parent class def __init__(self): print("This is the parent class: Machine") def feature1(self): print("It has lots of features") class SimpleMachine(Machine): # child class def __init__(self): # call super() function super().__init__() print("This is the child class: Simplemachine") def feature2(self): print("It has less features") simpleMachine = SimpleMachine() simpleMachine.feature1() simpleMachine.feature2()
Output This is the parent class: Machine This is the child class: Simplemachine Machine feature invoked SimpleMachine feature invoked
In the above program, the child class SimpleMachine
inherits certain characteristics and methods from the parent class Machine
. We can always add features according to the requirement.
For more details please refer to inheritance in Python in detail along with its types.
6. Encapsulation in Python
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
Encapsulation along with access modifiers enables the prevention of some specified data from being directly modified. It also helps with development by ensuring that if intended no other entity can modify the data and hence prevent possible unfortunate errors.
In Python, we use single or double underscore('_','__'
) for denoting the private attributes.
Let’s take an example to understand the concept.
class Price: def __init__(self): self.__price = 1200 def buy(self): print("Cost Price: {}".format(self.__price)) def updatePrice(self, newPrice): self.__price = newPrice p = Price() p.buy() p.__price = 1320 # Trying to modify value p.buy() p.updatePrice(2000) p.buy()
Output Cost Price: 1200 Cost Price: 1200 Cost Price: 2000
In the above program, the value of __price
was not changed by external changes. However, we can change the value using the setter method as we did in the second last statement.
6.1. What is Data Hiding in Python?
As we discussed encapsulation, let’s understand what exactly is data hiding. Data hiding is an advanced technique that helps users define data privacy from other classes and the outside world.
The main reason for such a feature is to control the access of members of a class. With data hiding, we provide only the knowledge that is required by the outer world. Through this, we make sure that data can be not accessed/modified if it is not allowed.
OOP supports three types of access layers for data and functions which are termed as public, private, and protected.
- Private data or function refers to such data which can’t be accessed outside the class.
- Public data or functions can be accessed from anywhere in the program.
- Protected members of a class are accessible from within the class and are also available to its sub-classes. No other environment is permitted access to it.
7. Polymorphism in Python
Polymorphism is made up of two words, one is ‘poly‘ and the other is ‘morph‘. The word poly signifies many and the word morph signifies shape. In total polymorphism specifies that a single task can be performed in various possible ways.
Suppose, we need to design different pots from the same type of clay. The pot can be in a cylindrical, oval, and spherical shape. Hence, we can use the same method to get the shape of different types of pots.
Let’s understand it with an example on Birds along with Inheritance.
class Bird: def intro(self): print("There are many types of birds.") def flight(self): print("Most of the birds can fly but some cannot.") class Sparrow(Bird): def flight(self): print("Sparrows can fly.") class Ostrich(Bird): def flight(self): print("Ostriches cannot fly.") obj_bird = Bird() obj_bird.intro() obj_bird.flight() obj_spr = Sparrow() obj_spr.intro() obj_spr.flight() obj_ost = Ostrich() obj_ost.intro() obj_ost.flight()
Output There are many types of birds. Most of the birds can fly but some cannot. There are many types of birds. Sparrows can fly. There are many types of birds. Ostriches cannot fly.
In the above example, we have used Bird
as the parent class and the other two classes override the function flight
and provide a custom implementation based on the type of the bird.
Polymorphism is classified into two categories:
- Overriding the data and function of Parent
- Overloading of an operator
The above example is just one way to achieve polymorphism but there are multiple other ways to achieve polymorphism in Python that we will discuss in detail in future articles.
8. Data Abstraction in Python
In python, the concept of data abstraction and encapsulation are synonyms of each other due to their similarity of tasks. They are said similar because the abstraction of data is created with the help of encapsulation.
Data abstraction refers to the hiding of internal information from the user and makes only the functions and other output visible.
We use the concept of abstraction in different classes. In return, the specific class encapsulates data and functions inside the class and hides the complex working information from the user. This concept makes the user focus on the result rather than the process working.
9. Conclusion
Finally, if we sum up, in this article we learned about different properties of OOP along with their implementation, we have covered:
- What is OOP and how can we use OOP in python along with its characteristics?
- Structural block or basic concepts of OOP?
- What is a class in OOP and how can we create our own class?
- What is an object in python?
- How does inheritance work in Python?
- What is Encapsulation in Python and how to implement it and also what is Data Hiding in python?
- What is the role of polymorphism in Python?
- How does Data Abstraction works in Python?
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?