Python OOPs Concepts With Examples
Table of Contents
- Introduction
- OOPs Concepts in Python
- Python OOPs Concepts Video
- Important Things to Know About Python OOPs Concepts
- Python OOPs FAQs
Introduction
Similar to any other general-purpose programming language, Python is also an object-oriented language. With Python, programmers can develop applications OOPs in Python using OOPs, and it allows them to create and use classes and objects.
OOPs in Python is a programming paradigm using classes and objects. Its purpose is to implement real-world entities and concepts, such as inheritance, encapsulation, abstraction, and polymorphism in programming.
The main idea behind OOPs concepts is to bind data and functions as a single unit so no other part of a code can access that section of the data. Moreover, it allows code reusability and has become a key technique for resolving issues through objects.
In this article, we will learn about different OOPs concepts in Python, their purpose, uses, and examples. So, let’s get started.
OOPs Concepts in Python
Main Object-Oriented Programming (OOPs) concepts in Python
-
Class
-
Objects
-
Method
-
Polymorphism
-
Encapsulation
-
Inheritance
-
Data Abstraction
1. Class
A class refers to a collection of objects. It is one of the important Python OOPs that contains a prototype or blueprint to create objects. Moreover, it is a logical entity with specified attributes and methods.
To explain a class in Python, let’s take an example. You need to track employees in an organisation based on different attributes, such as age, salary, gender, etc. In a list, the first element can represent their age, and the second element can show their salary.
When you need to track records for 100 employees, knowing the right element and adding more properties can be challenging. Therefore, a class is used to address this issue and make it more organised.
-
A class is created using the keyword class.
-
Attributes refer to variables that belong to a class.
-
These attributes are always public, and you can access them using a dot (.). For example, My class.Myattribute
Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
Example:
Here's an example of a simple class definition in Python:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def drive(self):
print(f"The {self.brand} {self.model} is driving.")
2. Objects
An object is an entity with a state and behaviour associated with it. An object can be any real-world thing, such as a table, pen, laptop, keyboard, chair, bottle, etc. Dictionaries, integers, arrays, strings, and floating-point numbers are also objects.
In simple terms, any single string or integer is an object. Similarly, anything in Python is an object as they have attributes and methods. A string ‘Hi there’, a list containing other objects, the number 18, and so on are objects. Many a time, we might not realise we are using objects.
To create an instance of a class, you can use the class name followed by parentheses:
my_car = Car("Toyota", "Camry")
An object is a crucial concept of OOPs with Python that contains:
-
Behaviour: Methods of an object represent behaviour. It shows the response of one object to another object.
-
State: Attributes of an object represent the state, which refers to the properties of objects.
-
Identity: It assigns a unique name to an object so that one object can interact with another easily.
3. Method
The next concept of object-oriented programming in Python is the method, which refers to the function associated with an object. A method is not different to a class instance, and any object can have methods in Python.
Methods are essential components of Python object-oriented programming (OOP) as they encapsulate the functionality associated with the objects.
Here are some key points to understand about methods:
-
Method Syntax:
A method is defined inside a class using the def keyword, similar to how functions are defined. However, methods always include a special first parameter, usually named self, which represents the instance of the class.
class MyClass:
def my_method(self, arg1, arg2):
# Method code goes here
-
Self Parameter:
The self parameter is a reference to the instance of the class. It allows methods to access the instance's attributes and other methods. By convention, self is the name used, but you can choose any other name as long as it is the first parameter in the method definition.
-
Accessing Attributes:
Inside a method, you can access the instance's attributes using the self parameter. For example, if a class has an attribute named attribute1, you can access it within a method as self.attribute1.
-
Calling Methods:
Methods are called on objects of the class using dot notation. When a method is called, the instance is automatically passed as the self parameter.
my_object = MyClass()
my_object.my_method(arg1, arg2) # Calling the method on the object
4. Inheritance
Inheritance is the most crucial OOPs concept in Python, which is similar to the real-life concept of inheritance. It means a child class acquiring properties and behaviours of an already existing class, known as a parent or base class.
Using inheritance, we can create a new class or derived class that has all the features and attributes of another class. It allows code reusability, so programmers don’t have to write code again.
-
Inheritance explains real-life relationships well.
-
We can easily add more features along with the ones acquired from the parent class without modifying the class.
-
We can reuse code rather than write the same code again.
-
Inheritance is transitive, which means if m class is derived from n class, then subclasses of m will automatically inherit from the n class.
Types of Inheritance
-
Single Inheritance: A single-level inheritance is the one where a child class inherits features and behaviours of a single parent class.
-
Multi-level Inheritance: This type of inheritance allows a child class to acquire properties of an immediate parent class, which will inherit properties of his parent or base class.
-
Hierarchical Inheritance: This level of inheritance involves more than one derived class inheriting properties and features of one parent class.
-
Multiple Inheritance: Here, a single child class inherits features and properties of more than one parent class.
5. Polymorphism
Polymorphism combines two words- ‘poly’, which means many and ‘morphs’, which means ‘shape’. Hence, polymorphism means to have multiple forms or when one task can be performed in several ways.
For example, in a class animal, all animals speak but in different ways. So, ‘speak’ is polymorphic and varies based on the animal. The abstract ‘animal’ may not speak, but the specific animal can, and there is a concrete implementation of the action ‘speak’.
Polymorphism is a fundamental concept in Python OOPs that allows objects of different classes to be treated as objects of a common superclass. It enables code to be written that can work with objects of multiple types, providing flexibility and extensibility in software design.
In Python, polymorphism is achieved through method overriding and method overloading. Let's explore these concepts:
-
Method Overriding:
Method overriding occurs when a subclass defines a method with the same name as a method in its superclass. The overridden method in the subclass provides a different implementation while having the same method signature (name and parameters) as the superclass method.
Example:
class Animal:
def sound(self):
print("Animal makes a sound.")
class Dog(Animal):
def sound(self):
print("Dog barks.")
class Cat(Animal):
def sound(self):
print("Cat meows.")
my_dog = Dog()
my_cat = Cat()
my_dog.sound() # Outputs: "Dog barks."
my_cat.sound() # Outputs: "Cat meows."
Explanation:
In this example, both the Dog and Cat classes inherit from the Animal class. They override the sound method and provide their own implementation. When the sound method is called on an object of the respective class, the overridden method is executed.
-
Method Overloading:
Method overloading refers to defining multiple methods with the same name but different parameters in a class. However, unlike some other programming languages, Python does not support explicit method overloading based on parameter types or counts. However, you can achieve a form of method overloading using default parameter values and variable arguments.
Example:
class Calculator:
def add(self, a, b):
return a + b
def add(self, a, b, c):
return a + b + c
my_calculator = Calculator()
print(my_calculator.add(2, 3)) # Raises TypeError: add() missing 1 required positional argument: 'c'
print(my_calculator.add(2, 3, 4)) # Outputs: 9
Explanation:
In this example, the Calculator class has two methods named add. The first method accepts two parameters, and the second method accepts three parameters. However, attempting to call the add method with only two arguments will result in a TypeError. This is because Python does not support method overloading based on the number of parameters alone.
6. Encapsulation
Encapsulation is among the important OOPs principles in Python and a fundamental concept. It means wrapping methods, code, and data within one unit to avoid accidental modifications.
Encapsulation restricts direct access to variables and methods, which prevents any accidental modification of data. So, the variable of an object can be changed only by an object’s method. These variables are called private variables. For example, a class encapsulates all the data, including functions and variables.
7. Data Abstraction
Data abstraction is used for hiding unnecessary or internal details of code from users and showing only functionalities or important information. Many often use data abstraction and encapsulation as synonyms, but both OOPs concepts are different.
Abstraction is achieved through encapsulation. Abstracting means assigning names to things, where the name represents the core functions. It is used when we don’t want to share all the information, especially sensitive details of code implementation and allow access to essential or required information.
Python OOPs Concepts Video
Here is a detailed video about OOPs concepts in Python:
Important Things to Know About Python OOPs Concepts
There are a few key points about Python OOPs concepts to remember:
-
It allows code reusability as the class is sharable.
-
It makes a program efficient and easy to understand.
-
It keeps data safe and secured through abstraction.
-
Polymorphism provides the same interface for various objects, which allows programmers to write efficient code.
Python OOPs FAQs
Here are some frequently asked questions related to OOPs in Python:
1. How do you make a Python class that is empty?
An empty class has no defined member. It is made by using the pass keyword, which does nothing in Python. You can create objects of the class outside it.
2. Does Python use access specifiers?
Python doesn’t use access specifiers, such as protected, private, or public. It doesn’t receive this information from variables. It uses a single (protected) or double underscore (private) as a prefix to variables to copy their behaviours. If a variable doesn’t have an underscore before its name, it is public by default.
3. What does a class object or instance mean?
A class instance is an object that must be generated to use a class. While creating a class instance, you must allocate RAM to store the contents of class variables. As the class object is created, data from instance variables are transferred to the object or instance. Each class instance is different, with distinct attributes and capabilities. Attributes refer to qualities, while capabilities are the functions that an object can carry out.
4. What are the major benefits of OOPs in Python?
Here are the advantages of OOPs concepts in Python:
-
They reduce code redundancy by enabling programmers to write clear and reusable code through inheritance.
-
Each OOPs object represents a different section of a code with its own logic and data to communicate with other concepts. Hence, eliminating complications in code.
-
OOPs are easy to visualise as they represent real-life situations and entities. For example, inheritance, abstraction, and objects are closely related to real-world situations.
5. What is an _init_ method?
All the properties of human objects defined in a method are known as init(). When you create a new object every time, init() sets its initial state by assigning a value you provide inside the properties of an object.
This means init() initialises a new instance of a class. It can take any number of parameters, but the first parameter has to be a variable always, known as self. It is a reference to the current instance of a class, which means the self-parameter points to the address of a class’ current object, so it can access the data and its variables.
This implies when you have even 1000 instances of a class, you can get their individual data because of self as it points to the address of a particular object and returns the respective value.
6. What are access modifiers?
Access modifiers restrict access to a class's methods and variables. There are three types of access modifiers in Python- private, public, and protected. You can’t have direct access to these modifiers but can achieve them using a single or double underscore.
A single underscore represents a protected class, whereas a double underscore represents a private class.
-
Public Member: It is accessible from anywhere outside the class.
-
Private Member: It is accessible within the class
-
Protected Member: It is accessible within the class and its sub-classes
7. What types of Python methods are there?
Python has three types of methods which are used to carry out different activities. They are:
-
Instance Methods
-
Class Methods
-
Static Methods
8. What is the meaning of Python's inheritance?
When a new class is derived from an existing class, it is called inheritance. The new class is known as the derived or child class, while the existing class is called the base or parent class.
A child class inherits the methods and variables of a parent class. In Python, each class is extended or inherited from the object class, which becomes a superclass once a new class is generated inside. One of the major benefits of inheritance of code accessibility.
9. What is a static variable or class variable?
All class instances have access to the class variables, which are declared at the beginning of a class in Python. Any changes made to one class variable affect variables of other instances. It is also possible to access class variables outside of a class by using the name of the class and class variable.