SlideShare a Scribd company logo
RAISONI GROUP OF INSTITUTIONS
Presentation
On
“Programming with Python”
By
Ms. H. C Kunwar
Assistant Professor
Department of Computer Engineering
G. H. Raisoni Polytechnic, Nagpur.
RAISONI GROUP OF INSTITUTIONS 1
RAISONI GROUP OF INSTITUTIONS 2
Department of Computer Engineering
Unit 5
(12 Marks)
Object Oriented Programming in Python
Lecture-1
RAISONI GROUP OF INSTITUTIONS 3
5.1 Creating Classes & Objects in Python
Python Objects and Classes :
Python is an object oriented programming language. Unlike procedure oriented
programming, where the main emphasis is on functions, object oriented programming
stresses on objects.
An object is simply a collection of data (variables) and methods (functions) that act
on those data. An object is also called an instance of a class and the process of
creating this object is called instantiation.
A class is a blueprint for that object. As many houses can be made from a house's
blueprint, we can create many objects from a class.
For Example : We can think of class as a sketch (prototype) of a house. It contains
all the details about the floors, doors, windows etc. Based on these descriptions we
build the house. House is the object.
RAISONI GROUP OF INSTITUTIONS 4
5.1 Creating Classes & Objects in Python
Defining a Class in Python :
Like function definitions begin with the def keyword in Python, class definitions
begin with a class keyword.
The first string inside the class is called docstring and has a brief description
about the class. Although not mandatory, this is highly recommended.
Here is a simple class definition.
A class creates a new local namespace where all its attributes are defined.
Attributes may be data or functions.
There are also special attributes in it that begins with double underscores __. For
example, __doc__ gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name.
This class object allows us to access the different attributes as well as to
instantiate new objects of that class.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
RAISONI GROUP OF INSTITUTIONS 5
5.1 Creating Classes & Objects in Python
Example :
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# Output: 10
print(Person.age)
# Output: <function Person.greet>
print(Person.greet)
# Output: 'This is my second class'
print(Person.__doc__)
Output
10
<function Person.greet at 0x7fc78c6e8160>
This is a person class
RAISONI GROUP OF INSTITUTIONS 6
5.1 Creating an Objects in Python
Creating an Object in Python :
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The
procedure to create an object is similar to a function call.
>>> harry = Person()
This will create a new object instance named harry. We can access the attributes of
objects using the object name prefix.
Attributes may be data or method. Methods of an object are corresponding
functions of that class.
This means to say, since Person.greet is a function object (attribute of class),
Person.greet will be a method object.
RAISONI GROUP OF INSTITUTIONS 7
5.1 Creating Objects in Python
Example :
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# create a new object of Person class
harry = Person()
# Output: <function Person.greet>
print(Person.greet)
# Output: <bound method Person.greet of
<__main__.Person object>>
print(harry.greet)
# Calling object's greet() method
# Output: Hello
harry.greet()
Output :
<function Person.greet at
0x7fd288e4e160>
<bound method Person.greet of
<__main__.Person object at
0x7fd288e9fa30>>
Hello
RAISONI GROUP OF INSTITUTIONS 8
5.1 Creating Objects in Python
Explanation :
You may have noticed the self parameter in function definition inside the class
but we called the method simply as harry.greet() without any arguments. It still
worked.
This is because, whenever an object calls its method, the object itself is passed as
the first argument. So, harry.greet() translates into Person.greet(harry).
In general, calling a method with a list of n arguments is equivalent to calling the
corresponding function with an argument list that is created by inserting the
method's object before the first argument.
For these reasons, the first argument of the function in class must be the object
itself. This is conventionally called self. It can be named otherwise but we highly
recommend to follow the convention.
RAISONI GROUP OF INSTITUTIONS 9
5.1 Creating Objects in Python
Example :
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " +
self.name)
p1 = Person("John", 36)
p1.myfunc()
Output :
Hello my name is John
Note: The self parameter is a reference to the current instance of the class, and is used
to access variables that belong to the class.
RAISONI GROUP OF INSTITUTIONS 10
5.1 Creating Objects in Python
The self Parameter :
The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class:
Example :
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Output :
Hello my name is John
RAISONI GROUP OF INSTITUTIONS 11
Constructors in Python :
Class functions that begin with double underscore __ are called special functions as
they have special meaning.
Of one particular interest is the __init__() function. This special function gets called
whenever a new object of that class is instantiated.
This type of function is also called constructors in Object Oriented Programming
(OOP). We normally use it to initialize all the variables.
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
5.1 Creating Constructors in Python
RAISONI GROUP OF INSTITUTIONS 12
5.1 Creating Constructors in Python
Output :
2+3j
(5, 0, 10)
Traceback (most recent call last):
File "<string>", line 27, in
<module>
print(num1.attr)
AttributeError: 'ComplexNumber'
object has no attribute 'attr'
RAISONI GROUP OF INSTITUTIONS 13
5.1 Deleting Attributes and Objects in Python
Deleting Attributes and Objects :
Any attribute of an object can be deleted anytime, using the del
statement.
>>> num1 = ComplexNumber(2,3)
>>> del num1.imag
>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag‘
>>> del ComplexNumber.get_data
>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'get_data'
RAISONI GROUP OF INSTITUTIONS 14
5.1 Creating Constructors in Python
We can even delete the object itself, using the del statement.
>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last):
...
NameError: name 'c1' is not defined
Actually, it is more complicated than that. When we do c1 =
ComplexNumber(1,3), a new instance object is created in memory and the name
c1 binds with it.
On the command del c1, this binding is removed and the name c1 is deleted from
the corresponding namespace. The object however continues to exist in memory
and if no other name is bound to it, it is later automatically destroyed.
This automatic destruction of unreferenced objects in Python is also called
garbage collection.
RAISONI GROUP OF INSTITUTIONS 15
5.2 Method Overloading in Python
Method Overloading :
Method Overloading is an
example of Compile time
polymorphism. In this, more
than one method of the same
class shares the same
method name having
different signatures. Method
overloading is used to add
more to the behavior of
methods and there is no
need of more than one class
for method overloading.
Note: Python does not
support method
overloading. We may
overload the methods but
can only use the latest
defined method.
# Function to take multiple arguments
def add(datatype, *args):
# if datatype is int # initialize answer as 0
if datatype =='int':
answer = 0
# if datatype is str # initialize answer as ''
if datatype =='str':
answer =''
# Traverse through the arguments
for x in args:
# This will do addition if the # arguments are int. Or
concatenation # if the arguments are str
answer = answer + x
print(answer)
# Integer
add('int', 5, 6)
# String
add('str', 'Hi ', 'Geeks') Output:
Output :
11
Hi Geeks
RAISONI GROUP OF INSTITUTIONS 16
5.1 Method Overloading in Python ?
Example :
class Employee :
def Hello_Emp(self,e_name=None):
if e_name is not None:
print("Hello "+e_name)
else:
print("Hello ")
emp1=Employee()
emp1.Hello_Emp()
emp1.Hello_Emp("Besant")
Output :
Hello
Hello Besant
Example:
class Area:
def find_area(self,a=None,b=None):
if a!=None and b!=None:
print("Area of Rectangle:",(a*b))
elif a!=None:
print("Area of square:",(a*a))
else:
print("Nothing to find")
obj1=Area()
obj1.find_area()
obj1.find_area(10)
obj1.find_area(10,20)
Output:
Nothing to find Area of a square: 100
Area of Rectangle: 200
RAISONI GROUP OF INSTITUTIONS 17
5.2 Method Overriding in Python ?
Method Overriding :
1. Method overriding is an example of run time polymorphism.
2. In this, the specific implementation of the method that is already provided
by the parent class is provided by the child class.
3. It is used to change the behavior of existing methods and there is a need for
at least two classes for method overriding.
4. In method overriding, inheritance always required as it is done between
parent class(superclass) and child class(child class) methods.
RAISONI GROUP OF INSTITUTIONS 18
5.2 Method Overriding in Python ?
class A:
def fun1(self):
print('feature_1 of class A')
def fun2(self):
print('feature_2 of class A')
class B(A):
# Modified function that is
# already exist in class A
def fun1(self):
print('Modified feature_1 of class A by class B')
def fun3(self):
print('feature_3 of class B')
# Create instance
obj = B()
# Call the override function
obj.fun1()
Output:
Modified version of
feature_1 of class A
by class B
RAISONI GROUP OF INSTITUTIONS 19
5.2 Method Overriding in Python ?
#Example : Python Method Overriding
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from
Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
Output :
RAISONI GROUP OF INSTITUTIONS 20
5.2 Method Overriding in Python ?
Example :
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
class Sales(Employee):
def message(self):
print('This Sales class is inherited from Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
print('------------')
sl = Sales()
sl.message()
Output :
RAISONI GROUP OF INSTITUTIONS 21
5.2 Method Overriding in Python ?
Sr. No. Method Overloading Method Overriding
1 Method overloading is a compile time
polymorphism
Method overriding is a run time
polymorphism.
2 It help to rise the readability of the
program.
While it is used to grant the
specific implementation of the
method which is already provided
by its parent class or super class.
3 It is occur within the class. While it is performed in two
classes with inheritance
relationship.
4 Method overloading may or may not
require inheritance.
While method overriding always
needs inheritance.
5 In this, methods must have same
name and different signature.
While in this, methods must have
same name and same signature.
6 In method overloading, return type
can or can not be same, but we must
have to change the parameter.
While in this, return type must be
same or co-variant.
RAISONI GROUP OF INSTITUTIONS 22
5.3 Data Hiding in Python ?
Data Hiding :
Data hiding in Python is the method to prevent access to specific users in the
application. Data hiding in Python is done by using a double underscore before
(prefix) the attribute name. This makes the attribute private/ inaccessible and hides
them from users.
Data hiding ensures exclusive data access to class members and protects object
integrity by preventing unintended or intended changes.
Example :
class MyClass:
__hiddenVar = 12
def add(self, increment):
self.__hiddenVar += increment
print (self.__hiddenVar)
myObject = MyClass()
myObject.add(3)
myObject.add (8)
print (myObject._MyClass__hiddenVar)
Output
15
23
23
RAISONI GROUP OF INSTITUTIONS 23
5.3 Data Hiding in Python ?
Data Hiding :
Data hiding
In Python, we use double underscore before the attributes name to make them
inaccessible/private or to hide them.
The following code shows how the variable __hiddenVar is hidden.
Example :
class MyClass:
__hiddenVar = 0
def add(self, increment):
self.__hiddenVar += increment
print (self.__hiddenVar)
myObject = MyClass()
myObject.add(3)
myObject.add (8)
print (myObject.__hiddenVar)
Output
3
Traceback (most recent call last):
11
File "C:/Users/TutorialsPoint1/~_1.py",
line 12, in <module>
print (myObject.__hiddenVar)
AttributeError: MyClass instance has no
attribute '__hiddenVar'
In the above program, we tried to access
hidden variable outside the class using
object and it threw an exception.
RAISONI GROUP OF INSTITUTIONS 24
5.4 Data Abstraction in Python ?
Data Abstraction :
Abstraction in Python is the process of hiding the real implementation of an
application from the user and emphasizing only on usage of it. For example,
consider you have bought a new electronic gadget.
Syntax :
RAISONI GROUP OF INSTITUTIONS 25
5.4 Data Abstraction in Python ?
Example :
from abc import ABC, abstractmethod
class Absclass(ABC):
def print(self,x):
print("Passed value: ", x)
@abstractmethod
def task(self):
print("We are inside Absclass task")
class test_class(Absclass):
def task(self):
print("We are inside test_class task")
class example_class(Absclass):
def task(self):
print("We are inside example_class task")
#object of test_class created
test_obj = test_class()
test_obj.task()
test_obj.print(100)
#object of example_class created
example_obj = example_class()
example_obj.task()
example_obj.print(200)
print("test_obj is instance of Absclass? ", isinstance(test_obj, Absclass))
RAISONI GROUP OF INSTITUTIONS 26
5.4 Data Abstraction in Python ?
Output :
RAISONI GROUP OF INSTITUTIONS 27
5.5 Inheritance & composition classes in Python ?
What is Inheritance (Is-A Relation) :
It is a concept of Object-Oriented Programming. Inheritance is a mechanism that
allows us to inherit all the properties from another class. The class from which the
properties and functionalities are utilized is called the parent class (also called as
Base Class). The class which uses the properties from another class is called as Child
Class (also known as Derived class). Inheritance is also called an Is-A Relation.
RAISONI GROUP OF INSTITUTIONS 28
5.5 Inheritance & composition classes in Python ?
Syntax :
# Parent class
class Parent :
# Constructor
# Variables of Parent class
# Methods
...
...
# Child class inheriting Parent class
class Child(Parent) :
# constructor of child class
# variables of child class
# methods of child class
RAISONI GROUP OF INSTITUTIONS 29
5.5 Inheritance & composition classes in Python ?
# parent class
class Parent:
# parent class method
def m1(self):
print('Parent Class Method called...')
# child class inheriting parent class
class Child(Parent):
# child class constructor
def __init__(self):
print('Child Class object created...')
# child class method
def m2(self):
print('Child Class Method called...')
# creating object of child class
obj = Child()
# calling parent class m1() method
obj.m1()
# calling child class m2() method
obj.m2()
Output :
Child Class object created...
Parent Class Method called...
Child Class Method called...
RAISONI GROUP OF INSTITUTIONS 30
5.5 Inheritance & composition classes in Python ?
What is Composition (Has-A Relation) :
It is one of the fundamental concepts of
Object-Oriented Programming.
In this we will describe a class that
references to one or more objects of other
classes as an Instance variable.
Here, by using the class name or by creating
the object we can access the members of one
class inside another class.
It enables creating complex types by
combining objects of different classes.
It means that a class Composite can contain
an object of another class Component.
This type of relationship is known as Has-A
Relation.
RAISONI GROUP OF INSTITUTIONS 31
5.5 Inheritance & composition classes in Python ?
Syntax :
class A :
# variables of class A
# methods of class A
...
...
class B :
# by using "obj" we can access member's of class A.
obj = A()
# variables of class B
# methods of class B
...
...
RAISONI GROUP OF INSTITUTIONS 32
5.5 Inheritance & composition classes in Python ?
class Component:
# composite class constructor
def __init__(self):
print('Component class object created...')
# composite class instance method
def m1(self):
print('Component class m1() method executed...')
class Composite:
# composite class constructor
def __init__(self):
# creating object of component class
self.obj1 = Component()
print('Composite class object also created...')
# composite class instance method
def m2(self):
print('Composite class m2() method executed...')
# calling m1() method of component class
self.obj1.m1()
# creating object of composite class
obj2 = Composite()
# calling m2() method of composite class
obj2.m2()
RAISONI GROUP OF INSTITUTIONS 33
5.6 Customization via inheritance specializing
inherited methods in Python ?
Customization via Inheritance specializing inherited methods:
1. The tree-searching model of inheritance turns out to be a great way to specialize
systems. Because inheritance finds names in subclasses before it checks
superclasses, subclasses can replace default behavior by redefining the
superclass's attributes.
2. In fact, you can build entire systems as hierarchies of classes, which are
extended by adding new external subclasses rather than changing existing logic
in place.
3. The idea of redefining inherited names leads to a variety of specialization
techniques.
1. For instance, subclasses may replace inherited attributes completely, provide
attributes that a superclass expects to find, and extend superclass methods by
calling back to the superclass from an overridden method.
RAISONI GROUP OF INSTITUTIONS 34
5.6 Customization via inheritance specializing
inherited methods in Python ?
Example- For specilaized inherited methods
class A:
"parent class" #parent class
def display(self):
print("This is base class")
class B(A):
"Child class" #derived class
def display(self):
A.display(self)
print("This is derived class")
obj=B() #instance of child
obj.display() #child calls overridden method
Output:
This is base class
This is derived class
Thank you !
RAISONI GROUP OF INSTITUTIONS 35
Ad

More Related Content

Similar to UNIT-5 object oriented programming lecture (20)

Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
Sasidhar Kothuru
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
Vijaykota11
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
The Ring programming language version 1.3 book - Part 5 of 88
The Ring programming language version 1.3 book - Part 5 of 88The Ring programming language version 1.3 book - Part 5 of 88
The Ring programming language version 1.3 book - Part 5 of 88
Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189
Mahmoud Samir Fayed
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
ID Bilişim ve Ticaret Ltd. Şti.
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
sadhana312471
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptx
abhishek364864
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in python
tuan vo
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Declarative Data Modeling in Python
Declarative Data Modeling in PythonDeclarative Data Modeling in Python
Declarative Data Modeling in Python
Joshua Forman
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
Mahmoud Samir Fayed
 
Master of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdfMaster of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdf
Krrai1
 
The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210
Mahmoud Samir Fayed
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
Vijaykota11
 
The Ring programming language version 1.3 book - Part 5 of 88
The Ring programming language version 1.3 book - Part 5 of 88The Ring programming language version 1.3 book - Part 5 of 88
The Ring programming language version 1.3 book - Part 5 of 88
Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189
Mahmoud Samir Fayed
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
sadhana312471
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptx
abhishek364864
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in python
tuan vo
 
Declarative Data Modeling in Python
Declarative Data Modeling in PythonDeclarative Data Modeling in Python
Declarative Data Modeling in Python
Joshua Forman
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
Mahmoud Samir Fayed
 
Master of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdfMaster of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdf
Krrai1
 
The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210
Mahmoud Samir Fayed
 

Recently uploaded (20)

Routing Riverdale - A New Bus Connection
Routing Riverdale - A New Bus ConnectionRouting Riverdale - A New Bus Connection
Routing Riverdale - A New Bus Connection
jzb7232
 
Compiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptxCompiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptx
RushaliDeshmukh2
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32
CircuitDigest
 
ZJIT: Building a Next Generation Ruby JIT
ZJIT: Building a Next Generation Ruby JITZJIT: Building a Next Generation Ruby JIT
ZJIT: Building a Next Generation Ruby JIT
maximechevalierboisv1
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
2025 Apply BTech CEC .docx
2025 Apply BTech CEC                 .docx2025 Apply BTech CEC                 .docx
2025 Apply BTech CEC .docx
tusharmanagementquot
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Compiler Design_Intermediate code generation new ppt.pptx
Compiler Design_Intermediate code generation new ppt.pptxCompiler Design_Intermediate code generation new ppt.pptx
Compiler Design_Intermediate code generation new ppt.pptx
RushaliDeshmukh2
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
Data Structures_Linear Data Structure Stack.pptx
Data Structures_Linear Data Structure Stack.pptxData Structures_Linear Data Structure Stack.pptx
Data Structures_Linear Data Structure Stack.pptx
RushaliDeshmukh2
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Reese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary_ The Role of Perseverance in Engineering Success.pdfReese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-02 notes [BCG402-CG&V].pdf
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-02 notes [BCG402-CG&V].pdfCOMPUTER GRAPHICS AND VISUALIZATION :MODULE-02 notes [BCG402-CG&V].pdf
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-02 notes [BCG402-CG&V].pdf
Alvas Institute of Engineering and technology, Moodabidri
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Routing Riverdale - A New Bus Connection
Routing Riverdale - A New Bus ConnectionRouting Riverdale - A New Bus Connection
Routing Riverdale - A New Bus Connection
jzb7232
 
Compiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptxCompiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptx
RushaliDeshmukh2
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32
CircuitDigest
 
ZJIT: Building a Next Generation Ruby JIT
ZJIT: Building a Next Generation Ruby JITZJIT: Building a Next Generation Ruby JIT
ZJIT: Building a Next Generation Ruby JIT
maximechevalierboisv1
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Compiler Design_Intermediate code generation new ppt.pptx
Compiler Design_Intermediate code generation new ppt.pptxCompiler Design_Intermediate code generation new ppt.pptx
Compiler Design_Intermediate code generation new ppt.pptx
RushaliDeshmukh2
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
Data Structures_Linear Data Structure Stack.pptx
Data Structures_Linear Data Structure Stack.pptxData Structures_Linear Data Structure Stack.pptx
Data Structures_Linear Data Structure Stack.pptx
RushaliDeshmukh2
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Reese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary_ The Role of Perseverance in Engineering Success.pdfReese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Ad

UNIT-5 object oriented programming lecture

  • 1. RAISONI GROUP OF INSTITUTIONS Presentation On “Programming with Python” By Ms. H. C Kunwar Assistant Professor Department of Computer Engineering G. H. Raisoni Polytechnic, Nagpur. RAISONI GROUP OF INSTITUTIONS 1
  • 2. RAISONI GROUP OF INSTITUTIONS 2 Department of Computer Engineering Unit 5 (12 Marks) Object Oriented Programming in Python Lecture-1
  • 3. RAISONI GROUP OF INSTITUTIONS 3 5.1 Creating Classes & Objects in Python Python Objects and Classes : Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stresses on objects. An object is simply a collection of data (variables) and methods (functions) that act on those data. An object is also called an instance of a class and the process of creating this object is called instantiation. A class is a blueprint for that object. As many houses can be made from a house's blueprint, we can create many objects from a class. For Example : We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
  • 4. RAISONI GROUP OF INSTITUTIONS 4 5.1 Creating Classes & Objects in Python Defining a Class in Python : Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword. The first string inside the class is called docstring and has a brief description about the class. Although not mandatory, this is highly recommended. Here is a simple class definition. A class creates a new local namespace where all its attributes are defined. Attributes may be data or functions. There are also special attributes in it that begins with double underscores __. For example, __doc__ gives us the docstring of that class. As soon as we define a class, a new class object is created with the same name. This class object allows us to access the different attributes as well as to instantiate new objects of that class. class MyNewClass: '''This is a docstring. I have created a new class''' pass
  • 5. RAISONI GROUP OF INSTITUTIONS 5 5.1 Creating Classes & Objects in Python Example : class Person: "This is a person class" age = 10 def greet(self): print('Hello') # Output: 10 print(Person.age) # Output: <function Person.greet> print(Person.greet) # Output: 'This is my second class' print(Person.__doc__) Output 10 <function Person.greet at 0x7fc78c6e8160> This is a person class
  • 6. RAISONI GROUP OF INSTITUTIONS 6 5.1 Creating an Objects in Python Creating an Object in Python : We saw that the class object could be used to access different attributes. It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call. >>> harry = Person() This will create a new object instance named harry. We can access the attributes of objects using the object name prefix. Attributes may be data or method. Methods of an object are corresponding functions of that class. This means to say, since Person.greet is a function object (attribute of class), Person.greet will be a method object.
  • 7. RAISONI GROUP OF INSTITUTIONS 7 5.1 Creating Objects in Python Example : class Person: "This is a person class" age = 10 def greet(self): print('Hello') # create a new object of Person class harry = Person() # Output: <function Person.greet> print(Person.greet) # Output: <bound method Person.greet of <__main__.Person object>> print(harry.greet) # Calling object's greet() method # Output: Hello harry.greet() Output : <function Person.greet at 0x7fd288e4e160> <bound method Person.greet of <__main__.Person object at 0x7fd288e9fa30>> Hello
  • 8. RAISONI GROUP OF INSTITUTIONS 8 5.1 Creating Objects in Python Explanation : You may have noticed the self parameter in function definition inside the class but we called the method simply as harry.greet() without any arguments. It still worked. This is because, whenever an object calls its method, the object itself is passed as the first argument. So, harry.greet() translates into Person.greet(harry). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method's object before the first argument. For these reasons, the first argument of the function in class must be the object itself. This is conventionally called self. It can be named otherwise but we highly recommend to follow the convention.
  • 9. RAISONI GROUP OF INSTITUTIONS 9 5.1 Creating Objects in Python Example : class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc() Output : Hello my name is John Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
  • 10. RAISONI GROUP OF INSTITUTIONS 10 5.1 Creating Objects in Python The self Parameter : The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: Example : Use the words mysillyobject and abc instead of self: class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc() Output : Hello my name is John
  • 11. RAISONI GROUP OF INSTITUTIONS 11 Constructors in Python : Class functions that begin with double underscore __ are called special functions as they have special meaning. Of one particular interest is the __init__() function. This special function gets called whenever a new object of that class is instantiated. This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize all the variables. class ComplexNumber: def __init__(self, r=0, i=0): self.real = r self.imag = i def get_data(self): print(f'{self.real}+{self.imag}j') 5.1 Creating Constructors in Python
  • 12. RAISONI GROUP OF INSTITUTIONS 12 5.1 Creating Constructors in Python Output : 2+3j (5, 0, 10) Traceback (most recent call last): File "<string>", line 27, in <module> print(num1.attr) AttributeError: 'ComplexNumber' object has no attribute 'attr'
  • 13. RAISONI GROUP OF INSTITUTIONS 13 5.1 Deleting Attributes and Objects in Python Deleting Attributes and Objects : Any attribute of an object can be deleted anytime, using the del statement. >>> num1 = ComplexNumber(2,3) >>> del num1.imag >>> num1.get_data() Traceback (most recent call last): ... AttributeError: 'ComplexNumber' object has no attribute 'imag‘ >>> del ComplexNumber.get_data >>> num1.get_data() Traceback (most recent call last): ... AttributeError: 'ComplexNumber' object has no attribute 'get_data'
  • 14. RAISONI GROUP OF INSTITUTIONS 14 5.1 Creating Constructors in Python We can even delete the object itself, using the del statement. >>> c1 = ComplexNumber(1,3) >>> del c1 >>> c1 Traceback (most recent call last): ... NameError: name 'c1' is not defined Actually, it is more complicated than that. When we do c1 = ComplexNumber(1,3), a new instance object is created in memory and the name c1 binds with it. On the command del c1, this binding is removed and the name c1 is deleted from the corresponding namespace. The object however continues to exist in memory and if no other name is bound to it, it is later automatically destroyed. This automatic destruction of unreferenced objects in Python is also called garbage collection.
  • 15. RAISONI GROUP OF INSTITUTIONS 15 5.2 Method Overloading in Python Method Overloading : Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading. Note: Python does not support method overloading. We may overload the methods but can only use the latest defined method. # Function to take multiple arguments def add(datatype, *args): # if datatype is int # initialize answer as 0 if datatype =='int': answer = 0 # if datatype is str # initialize answer as '' if datatype =='str': answer ='' # Traverse through the arguments for x in args: # This will do addition if the # arguments are int. Or concatenation # if the arguments are str answer = answer + x print(answer) # Integer add('int', 5, 6) # String add('str', 'Hi ', 'Geeks') Output: Output : 11 Hi Geeks
  • 16. RAISONI GROUP OF INSTITUTIONS 16 5.1 Method Overloading in Python ? Example : class Employee : def Hello_Emp(self,e_name=None): if e_name is not None: print("Hello "+e_name) else: print("Hello ") emp1=Employee() emp1.Hello_Emp() emp1.Hello_Emp("Besant") Output : Hello Hello Besant Example: class Area: def find_area(self,a=None,b=None): if a!=None and b!=None: print("Area of Rectangle:",(a*b)) elif a!=None: print("Area of square:",(a*a)) else: print("Nothing to find") obj1=Area() obj1.find_area() obj1.find_area(10) obj1.find_area(10,20) Output: Nothing to find Area of a square: 100 Area of Rectangle: 200
  • 17. RAISONI GROUP OF INSTITUTIONS 17 5.2 Method Overriding in Python ? Method Overriding : 1. Method overriding is an example of run time polymorphism. 2. In this, the specific implementation of the method that is already provided by the parent class is provided by the child class. 3. It is used to change the behavior of existing methods and there is a need for at least two classes for method overriding. 4. In method overriding, inheritance always required as it is done between parent class(superclass) and child class(child class) methods.
  • 18. RAISONI GROUP OF INSTITUTIONS 18 5.2 Method Overriding in Python ? class A: def fun1(self): print('feature_1 of class A') def fun2(self): print('feature_2 of class A') class B(A): # Modified function that is # already exist in class A def fun1(self): print('Modified feature_1 of class A by class B') def fun3(self): print('feature_3 of class B') # Create instance obj = B() # Call the override function obj.fun1() Output: Modified version of feature_1 of class A by class B
  • 19. RAISONI GROUP OF INSTITUTIONS 19 5.2 Method Overriding in Python ? #Example : Python Method Overriding class Employee: def message(self): print('This message is from Employee Class') class Department(Employee): def message(self): print('This Department class is inherited from Employee') emp = Employee() emp.message() print('------------') dept = Department() dept.message() Output :
  • 20. RAISONI GROUP OF INSTITUTIONS 20 5.2 Method Overriding in Python ? Example : class Employee: def message(self): print('This message is from Employee Class') class Department(Employee): def message(self): print('This Department class is inherited from Employee') class Sales(Employee): def message(self): print('This Sales class is inherited from Employee') emp = Employee() emp.message() print('------------') dept = Department() dept.message() print('------------') sl = Sales() sl.message() Output :
  • 21. RAISONI GROUP OF INSTITUTIONS 21 5.2 Method Overriding in Python ? Sr. No. Method Overloading Method Overriding 1 Method overloading is a compile time polymorphism Method overriding is a run time polymorphism. 2 It help to rise the readability of the program. While it is used to grant the specific implementation of the method which is already provided by its parent class or super class. 3 It is occur within the class. While it is performed in two classes with inheritance relationship. 4 Method overloading may or may not require inheritance. While method overriding always needs inheritance. 5 In this, methods must have same name and different signature. While in this, methods must have same name and same signature. 6 In method overloading, return type can or can not be same, but we must have to change the parameter. While in this, return type must be same or co-variant.
  • 22. RAISONI GROUP OF INSTITUTIONS 22 5.3 Data Hiding in Python ? Data Hiding : Data hiding in Python is the method to prevent access to specific users in the application. Data hiding in Python is done by using a double underscore before (prefix) the attribute name. This makes the attribute private/ inaccessible and hides them from users. Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes. Example : class MyClass: __hiddenVar = 12 def add(self, increment): self.__hiddenVar += increment print (self.__hiddenVar) myObject = MyClass() myObject.add(3) myObject.add (8) print (myObject._MyClass__hiddenVar) Output 15 23 23
  • 23. RAISONI GROUP OF INSTITUTIONS 23 5.3 Data Hiding in Python ? Data Hiding : Data hiding In Python, we use double underscore before the attributes name to make them inaccessible/private or to hide them. The following code shows how the variable __hiddenVar is hidden. Example : class MyClass: __hiddenVar = 0 def add(self, increment): self.__hiddenVar += increment print (self.__hiddenVar) myObject = MyClass() myObject.add(3) myObject.add (8) print (myObject.__hiddenVar) Output 3 Traceback (most recent call last): 11 File "C:/Users/TutorialsPoint1/~_1.py", line 12, in <module> print (myObject.__hiddenVar) AttributeError: MyClass instance has no attribute '__hiddenVar' In the above program, we tried to access hidden variable outside the class using object and it threw an exception.
  • 24. RAISONI GROUP OF INSTITUTIONS 24 5.4 Data Abstraction in Python ? Data Abstraction : Abstraction in Python is the process of hiding the real implementation of an application from the user and emphasizing only on usage of it. For example, consider you have bought a new electronic gadget. Syntax :
  • 25. RAISONI GROUP OF INSTITUTIONS 25 5.4 Data Abstraction in Python ? Example : from abc import ABC, abstractmethod class Absclass(ABC): def print(self,x): print("Passed value: ", x) @abstractmethod def task(self): print("We are inside Absclass task") class test_class(Absclass): def task(self): print("We are inside test_class task") class example_class(Absclass): def task(self): print("We are inside example_class task") #object of test_class created test_obj = test_class() test_obj.task() test_obj.print(100) #object of example_class created example_obj = example_class() example_obj.task() example_obj.print(200) print("test_obj is instance of Absclass? ", isinstance(test_obj, Absclass))
  • 26. RAISONI GROUP OF INSTITUTIONS 26 5.4 Data Abstraction in Python ? Output :
  • 27. RAISONI GROUP OF INSTITUTIONS 27 5.5 Inheritance & composition classes in Python ? What is Inheritance (Is-A Relation) : It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all the properties from another class. The class from which the properties and functionalities are utilized is called the parent class (also called as Base Class). The class which uses the properties from another class is called as Child Class (also known as Derived class). Inheritance is also called an Is-A Relation.
  • 28. RAISONI GROUP OF INSTITUTIONS 28 5.5 Inheritance & composition classes in Python ? Syntax : # Parent class class Parent : # Constructor # Variables of Parent class # Methods ... ... # Child class inheriting Parent class class Child(Parent) : # constructor of child class # variables of child class # methods of child class
  • 29. RAISONI GROUP OF INSTITUTIONS 29 5.5 Inheritance & composition classes in Python ? # parent class class Parent: # parent class method def m1(self): print('Parent Class Method called...') # child class inheriting parent class class Child(Parent): # child class constructor def __init__(self): print('Child Class object created...') # child class method def m2(self): print('Child Class Method called...') # creating object of child class obj = Child() # calling parent class m1() method obj.m1() # calling child class m2() method obj.m2() Output : Child Class object created... Parent Class Method called... Child Class Method called...
  • 30. RAISONI GROUP OF INSTITUTIONS 30 5.5 Inheritance & composition classes in Python ? What is Composition (Has-A Relation) : It is one of the fundamental concepts of Object-Oriented Programming. In this we will describe a class that references to one or more objects of other classes as an Instance variable. Here, by using the class name or by creating the object we can access the members of one class inside another class. It enables creating complex types by combining objects of different classes. It means that a class Composite can contain an object of another class Component. This type of relationship is known as Has-A Relation.
  • 31. RAISONI GROUP OF INSTITUTIONS 31 5.5 Inheritance & composition classes in Python ? Syntax : class A : # variables of class A # methods of class A ... ... class B : # by using "obj" we can access member's of class A. obj = A() # variables of class B # methods of class B ... ...
  • 32. RAISONI GROUP OF INSTITUTIONS 32 5.5 Inheritance & composition classes in Python ? class Component: # composite class constructor def __init__(self): print('Component class object created...') # composite class instance method def m1(self): print('Component class m1() method executed...') class Composite: # composite class constructor def __init__(self): # creating object of component class self.obj1 = Component() print('Composite class object also created...') # composite class instance method def m2(self): print('Composite class m2() method executed...') # calling m1() method of component class self.obj1.m1() # creating object of composite class obj2 = Composite() # calling m2() method of composite class obj2.m2()
  • 33. RAISONI GROUP OF INSTITUTIONS 33 5.6 Customization via inheritance specializing inherited methods in Python ? Customization via Inheritance specializing inherited methods: 1. The tree-searching model of inheritance turns out to be a great way to specialize systems. Because inheritance finds names in subclasses before it checks superclasses, subclasses can replace default behavior by redefining the superclass's attributes. 2. In fact, you can build entire systems as hierarchies of classes, which are extended by adding new external subclasses rather than changing existing logic in place. 3. The idea of redefining inherited names leads to a variety of specialization techniques. 1. For instance, subclasses may replace inherited attributes completely, provide attributes that a superclass expects to find, and extend superclass methods by calling back to the superclass from an overridden method.
  • 34. RAISONI GROUP OF INSTITUTIONS 34 5.6 Customization via inheritance specializing inherited methods in Python ? Example- For specilaized inherited methods class A: "parent class" #parent class def display(self): print("This is base class") class B(A): "Child class" #derived class def display(self): A.display(self) print("This is derived class") obj=B() #instance of child obj.display() #child calls overridden method Output: This is base class This is derived class
  • 35. Thank you ! RAISONI GROUP OF INSTITUTIONS 35