Python Object Oriented Programming
In Python, object-oriented Programming (OOPs) is a programming paradigm that
uses objects and classes in programming.The main concept of OOPs is to bind
the data and the functions that work on that together as a single unit so that no
other part of the code can access this data.
Main Concepts of Object-Oriented Programming
● Class
● Objects
● Polymorphism
● Encapsulation
● Inheritance
● Data Abstraction
Class :A class is a collection of objects. A class contains the blueprints or the
prototype from which the objects are being created. It is a logical entity that
contains some attributes and methods.
class classname:
Statement 1
…..
Statement n
Object
An object (instance) is an instantiation of a class. When class is defined, only
the description for the object is defined. Therefore, no memory or storage is
allocated.
Methods
Methods are functions defined inside the body of a class. They are used to
define the behaviors of an object.
Eg:
class Hello:
def display(self):
print(“Welcome”)
obj=Hello() #creating object of the class
[Link]() #call instance method
Constructors in Python: Constructors are generally used for instantiating
an object. The task of constructors is to initialize(assign values) to the data
members of the class when an object of the class is created. In Python the
__init__() method is called the constructor and is always called when an object is
created.
Types of constructors :
● default constructor: The default constructor is a simple constructor
which doesn’t accept any arguments. Its definition has only one
argument which is a reference to the instance being constructed.
● parameterized constructor: constructor with parameters is known as
parameterized constructor. The parameterized constructor takes its first
argument as a reference to the instance being constructed known as
self and the rest of the arguments are provided by the programmer.
●
● class Hello:
● def __init__(self): # default constructor
● self.s = "Welcome"
● def display(self): # a method for printing data members
● print(self.s)
● obj = Hello() # creating object of the class
● [Link]() # calling the instance method using the object obj
parameterized constructor
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
[Link] = f
[Link] = s
def calculate(self):
[Link] = [Link] + [Link]
print([Link])
# creating object of the class,this will invoke parameterized constructor
obj1 = Addition(1000, 2000)
[Link]()
Class and Instance Variables in Python
Instance variables:Instance variables are owned by instances of the class. This
means that for each object or instance of a class, the instance variables are
[Link] variables are defined within methods.
class student:
def __init__(self,m1,m2,m3):
[Link]=m1 #instance variables
[Link]=m2
[Link]=m3
def display_physics(self):
print([Link])
obj=student(23,45,40)
obj.display_physics() #print 23
obj1=student(50,34,45)
obj1.display_physics() #print 50
Instance variables, owned by objects of the class, allow for each object or
instance to have different values assigned to those variables.
Class Variables:Class variables are defined within the [Link] variables are
shared by all instances of the class. It is defined before the constructor method
and other methods.
class student:
college="CEC" #class/static variable
def __init__(self,m1,m2): #instance variables
[Link]=m1
[Link]=m2
obj=student(34,43)
print([Link]) #access static variables only by using object
print([Link]) #access class variables either by using object or by using class name
print([Link])
Types of methods in python:
Instance method :performs a set of actions on the data/value provided by the
instance variables. If we use instance variables inside a method, such
methods are called instance methods.
Class method:If we use all class variables inside a method,such methods are
called class methods.
Static method is a general utility method that performs a task in isolation.
This method doesn’t have access to the instance and class variable.
class student:
college="CEC" #class variable
def __init__(self,m1,m2,m3):
[Link]=m1 #instance variables
[Link]=m2
def avg(self): #instance method
[Link]=([Link]+[Link])/2
print([Link])
@classmethod #class method
def getcollege(cls):
print([Link])
@staticmethod #static method
def info():
print("This is student class")
obj=student(34,50,43)
[Link]() #access instance method by using object
[Link]() #access class method by using class
[Link]() #access static method by using object or class
Accessor and Mutator methods
Accessor Method(getter):This method is used to access the state of the
[Link], this method cannot change the state of the object, it can only
access the data hidden. We can name these methods with the word get.
Mutator Method: This method is used to mutate/modify the state of an object
It can set the value of a variable instantly to a new value. This method is also
called an update method. Moreover, we can name these methods with the
word set.
class student:
college="CEC"
def __init__(self,m1,m2,m3):
[Link]=m1
[Link]=m2
[Link]=m3
def get_method(self): #Defining Accessor Method
print([Link])
def set_method(self,value): #Defining Mutator Method
[Link]=value
print([Link])
obj=student(34,50,43)
[Link]()
[Link](20)
Inheritance: Inheritance is the capability of one class to derive or inherit the
properties from another [Link] provides the reusability of a code. We don’t
have to write the same code again and again. Also, it allows us to add more
features to a class without modifying [Link] is transitive in nature, which means that
if class B inherits from another class A, then all the subclasses of B would
automatically inherit from class A.
Different types of Inheritance:
[Link] inheritance: When a child class inherits from only one parent class, it is
called single inheritance.
class A:
def method_A(self):
print("Parent class A")
class B(A):
def method_B(self):
print("Child class B")
obj=B()
obj.method_A()
obj.method_B()
[Link] inheritance: When we have a child and grandchild relationship.
class A(object):
def method_A(self):
print("class A")
class B(A):
def method_B(self):
print("class B")
class C(B):
def method_C(self):
print("class C")
obj=C()
obj.method_A()
obj.method_B()
obj.method_C()
[Link] inheritances: When a child class inherits from multiple parent
classes, it is called multiple inheritances.
class A:
def method_A(self):
print("class A")
class B:
def method_B(self):
print("class B")
class C(A,B):
def method_C(self):
print("child class of A & B")
obj=C()
obj.method_A()
obj.method_B()
obj.method_C()
4. Hierarchical inheritance More than one derived class are created from a
single base
class A:
def method_A(self):
print("class A")
class B(A):
def method_B(self):
print("Class B=Child class of A")
class C(A):
def method_C(self):
print("Class C=child class of A")
obj=C()
obj.method_A()
obj.method_C()
obj1=B()
obj1.method_A()
obj1.method_B()
5. Hybrid inheritance: This form combines more than one form of inheritance.
Basically, it is a blend of more than one type of inheritance
Constructor overriding
class A:
def __init__(self):
print("Constructor A")
def method_A(self):
print("Parent class A")
class B(A):
def __init__(self):
super().__init__()
print("Constructor B")
def method_B(self):
print("Child class B")
obj=B()
obj.method_A()
obj.method_B()
In the above example, we are having a constructor in base and inherited [Link]
created an object for the child class. When the object is created, it will call the child
class [Link] we want to call the base class constructor. We use, super() function.
Polymorphism
Method Overloading: Two or more methods have the same name but different numbers of
parameters or different types of parameters, or both. These methods are called overloaded
methods and this is called method [Link] does not support method overloading
by default. But there are different ways to achieve method overloading in Python.
class A:
def add(self,a=0,b=0):
s=0
if a!=0 and b!=0:
s=a+b
else:
s=a
print(s)
obj=A()
[Link](1)
[Link]()
[Link](2,3)
Method overriding in python: In Python, Polymorphism lets us define
methods in the child class that have the same name as the methods in the parent
[Link], in inheritance hierarchy, derived class defines a method with the same
name as a function in its base class, there is overriding. The function defined in
the derived class hides its definition in the base class. super() method in function
overriding can be used to call the overridden function in the following manner,
class A:
def show(self):
print("Show Parentclass A")
class B(A):
def show(self):
super().show()
print("Show Childclass B")
obj=B()
[Link]()
Abstract class in python:
An abstract class can be considered as a blueprint for other classes. It allows
you to create a set of methods that must be created within any child classes built
from the abstract class. A class which contains one or more abstract methods is
called an abstract class. An abstract method is a method that has a declaration
but does not have an implementation. While we are designing large functional
units we use an abstract class. When we want to provide a common interface for
different implementations of a component, we use an abstract class.
How Abstract Base classes work :
By default, Python does not provide abstract classes. Python comes with a
module that provides the base for defining Abstract Base classes(ABC) and that
module name is ABC. ABC works by decorating methods of the base class as
abstract and then registering concrete classes as implementations of the abstract
base. A method becomes abstract when decorated with the keyword
@abstractmethod. For Example,
from abc import ABC,abstractmethod
class computer(ABC):
@abstractmethod
def cpu(self):
pass
class laptop(computer):
def cpu(self):
print("Its running")
obj=laptop()
[Link]()
Exception:
Exceptions: Exceptions are raised when the program is syntactically correct, but
the code resulted in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.
a=6
b=0
print(a/b)
print("Stop")
The above example raises the ZeroDivisionError as we are trying to divide a
number by 0.
Handle a single Exception:
Try and Except Statement –Try and except statements are used to catch and
handle exceptions in Python. Statements that can raise exceptions are kept
inside the try clause and the statements that handle the exception are written
inside the except [Link] provides a keyword finally, which is always
executed after the try and except blocks. The finally block always executes
after normal termination of try block or after try block terminates due to some
exception.
a=6
b=2
try:
print(a/b)
a=int(input("Enter the number"))
print(a)
except Exception as e:
print("Division by zero is not possible",e)
finally:
print("Stop")
Handle multiple Exceptions:
A try statement can have more than one except clause, to specify handlers for
different exceptions. Please note that at most one handler will be executed. For
example,
a=6
b=2
try:
print(a/b)
a=int(input("Enter the number")
print(a)
except ZeroDivisionError as e:
print("Division by zero is not possible",e)
except ValueError as e:
print("Invalid input",e)
except Exception as e:
print("Error",e)
finally:
print("Stop")