Python OOPs Concepts
Like other general-purpose programming languages, Python has also been an
object-oriented language since its beginning. It allows us to develop applications using
an Object-Oriented approach. In Python, we can easily create and use classes and
objects.
An object-oriented paradigm is to design the program using classes and objects. The
object is related to real-word entities such as books, house, pencil, etc. The oops
concept focuses on writing the reusable code. It is a widespread technique to solve the
problem by creating objects.
Major principles of object-oriented programming systems are given below.
○ Class
○ Object
○ Method
○ Inheritance
○ Polymorphism
○ Data Abstraction
○ Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
1. class ClassName:
2. <statement-1>
3. .
4. .
5. <statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
When we define a class, it needs to create an object to allocate the memory. Consider
the following example.
Example:
1. class car:
2. def __init__(self,modelname, year):
3. self.modelname = modelname
4. self.year = year
5. def display(self):
6. print(self.modelname,self.year)
7.
8. c1 = car("Toyota", 2016)
9. c1.display()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes
modelname and year. We have created a c1 object to access the class attribute. The c1
object will allocate memory for these values. We will learn more about class and object
in the next tutorial.
Method
The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which
simulates the real-world concept of inheritance. It specifies that the child object
acquires all the properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior
of another class. The new class is known as a derived class or child class, and the one
whose properties are acquired is known as a base class or parent class.
It provides the re-usability of the code.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph
means shape. By polymorphism, we understand that one task can be performed in
different ways. For example - you have a class animal, and all animals speak. But they
speak differently. Here, the "speak" behavior is polymorphic in a sense and depends on
the animal. So, the abstract "animal" concept does not actually "speak", but specific
animals (like dogs and cats) have a concrete implementation of the action "speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does
Classes and Objects in Python
Python is an object-oriented programming language that offers classes, which are a
potent tool for writing reusable code. To describe objects with shared characteristics
and behaviors, classes are utilized. We shall examine Python's ideas of classes and
objects in this article.
Classes in Python:
In Python, a class is a user-defined data type that contains both the data itself and the
methods that may be used to manipulate it. In a sense, classes serve as a template to
create objects. They provide the characteristics and operations that the objects will
employ.
Suppose a class is a prototype of a building. A building contains all the details about the
floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many
objects of this class.
Creating Classes in Python
In Python, a class can be created by using the keyword class, followed by the class
name. The syntax to create a class is given below.
Syntax
1. class ClassName:
2. #statement_suite
In Python, we must notice that each class is associated with a documentation string
which can be accessed by using <class-name>.__doc__. A class contains a statement
suite including fields, constructor, function, etc. definition.
Example:
Code:
1. class Person:
2. def __init__(self, name, age):
3. # This is the constructor method that is called when creating a new Person
object
4. # It takes two parameters, name and age, and initializes them as attributes
of the object
5. self.name = name
6. self.age = age
7. def greet(self):
8. # This is a method of the Person class that prints a greeting message
9. print("Hello, my name is " + self.name)
Name and age are the two properties of the Person class. Additionally, it has a function
called greet that prints a greeting.
Objects in Python:
An object is a particular instance of a class with unique characteristics and functions.
After a class has been established, you may make objects based on it. By using the
class constructor, you may create an object of a class in Python. The object's attributes
are initialized in the constructor, which is a special procedure with the name __init__.
Syntax:
1. # Declare an object of a class
2. object_name = Class_Name(arguments)
Example:
Code:
1. class Person:
2. def __init__(self, name, age):
3. self.name = name
4. self.age = age
5. def greet(self):
6. print("Hello, my name is " + self.name)
7.
8. # Create a new instance of the Person class and assign it to the variable person1
9. person1 = Person("Ayan", 25)
10. person1.greet()
Output:
"Hello, my name is Ayan"
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of any
function which belongs to the class.
_ _init_ _ method
In order to make an instance of a class in Python, a specific function called __init__ is
called. Although it is used to set the object's attributes, it is often referred to as a
constructor.
The self-argument is the only one required by the __init__ method. This argument refers
to the newly generated instance of the class. To initialise the values of each attribute
associated with the objects, you can declare extra arguments in the __init__ method.
Class and Instance Variables
All instances of a class exchange class variables. They function independently of any
class methods and may be accessed through the use of the class name. Here's an
illustration:
Code:
1. class Person:
2. count = 0 # This is a class variable
3.
4. def __init__(self, name, age):
5. self.name = name # This is an instance variable
6. self.age = age
7. Person.count += 1 # Accessing the class variable using the name of the
class
8. person1 = Person("Ayan", 25)
9. person2 = Person("Bobby", 30)
10. print(Person.count)
Output:
Whereas, instance variables are specific to each instance of a class. They are specified
using the self-argument in the __init__ method. Here's an illustration:
Code:
1. class Person:
2. def __init__(self, name, age):
3. self.name = name # This is an instance variable
4. self.age = age
5. person1 = Person("Ayan", 25)
6. person2 = Person("Bobby", 30)
7. print(person1.name)
8. print(person2.age)
Output:
Ayan
30
Class variables are created separately from any class methods and are shared by all
class copies. Every instance of a class has its own instance variables, which are
specified in the __init__ method utilising the self-argument.
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides
code reusability to the program because we can use an existing class to create a new
class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class. In this section of the
tutorial, we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name. Consider the following syntax to inherit a base
class into the derived class.
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.
Syntax
1. class derived-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>
Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
Multilevel inheritance is possible in python like other object-oriented languages.
Multilevel inheritance is achieved when a derived class inherits another derived class.
There is no limit on the number of levels up to which the multi-level inheritance is
archived in python.
The syntax of multilevel inheritance is given below.
Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
7. .
8. .
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Python Multiple inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.
The syntax to perform multiple inheritance is given below.
Syntax
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
10. <class-suite>
11.
12. class Derived(Base1, Base2, ...... BaseN):
13. <class-suite>
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))
Output:
30
200
0.5
The issubclass(sub,sup) method
The issubclass(sub, sup) method is used to check the relationships between the
specified classes. It returns true if the first class is the subclass of the second class,
and false otherwise.
Consider the following example.
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(issubclass(Derived,Calculation2))
12. print(issubclass(Calculation1,Calculation2))
Output:
True
False
The isinstance (obj, class) method
The isinstance() method is used to check the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.
Consider the following example.
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(isinstance(d,Derived))
Output:
True
Method Overriding
We can provide some specific implementation of the parent class method in our child
class. When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to perform
method overriding in the scenario where the different definition of a parent class
method is needed in the child class.
Consider the following example to perform method overriding in python.
Example
1. class Animal:
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. d.speak()
Output:
Barking
Real Life Example of method overriding
1. class Bank:
2. def getroi(self):
3. return 10;
4. class SBI(Bank):
5. def getroi(self):
6. return 7;
7.
8. class ICICI(Bank):
9. def getroi(self):
10. return 8;
11. b1 = Bank()
12. b2 = SBI()
13. b3 = ICICI()
14. print("Bank Rate of interest:",b1.getroi());
15. print("SBI Rate of interest:",b2.getroi());
16. print("ICICI Rate of interest:",b3.getroi());
Output:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8