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

More Related Content

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

Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Slide - FPT University - PFP191 - Chapter 11 - Objects
Slide - FPT University - PFP191 - Chapter 11 - ObjectsSlide - FPT University - PFP191 - Chapter 11 - Objects
Slide - FPT University - PFP191 - Chapter 11 - Objects
cMai28
 
Python3
Python3Python3
Python3
Ruchika Sinha
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMINGOOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Module 3,4.pptx
Module 3,4.pptxModule 3,4.pptx
Module 3,4.pptx
SandeepR95
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.pptLecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.pptLecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
Inzamam Baig
 
About Python
About PythonAbout Python
About Python
Shao-Chuan Wang
 
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
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
Advance python
Advance pythonAdvance python
Advance python
pulkit agrawal
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
baabtra.com - No. 1 supplier of quality freshers
 
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
 
Python 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptxPython 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Python Advanced Course - part I.pdf for Python
Python Advanced Course - part I.pdf for PythonPython Advanced Course - part I.pdf for Python
Python Advanced Course - part I.pdf for Python
JunZhao68
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Slide - FPT University - PFP191 - Chapter 11 - Objects
Slide - FPT University - PFP191 - Chapter 11 - ObjectsSlide - FPT University - PFP191 - Chapter 11 - Objects
Slide - FPT University - PFP191 - Chapter 11 - Objects
cMai28
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMINGOOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Module 3,4.pptx
Module 3,4.pptxModule 3,4.pptx
Module 3,4.pptx
SandeepR95
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.pptLecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.pptLecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
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
 
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
 
Python 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptxPython 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Python Advanced Course - part I.pdf for Python
Python Advanced Course - part I.pdf for PythonPython Advanced Course - part I.pdf for Python
Python Advanced Course - part I.pdf for Python
JunZhao68
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
IRAH34
 

Recently uploaded (20)

fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
FISICA ESTATICA DESING LOADS CAPITULO 2.
FISICA ESTATICA DESING LOADS CAPITULO 2.FISICA ESTATICA DESING LOADS CAPITULO 2.
FISICA ESTATICA DESING LOADS CAPITULO 2.
maldonadocesarmanuel
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
ijccmsjournal
 
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra OpticaPruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
OmarAlfredoDelCastil
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
BeHappy728244
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Webinar On Steel Melting IIF of steel for rdso
Webinar  On Steel  Melting IIF of steel for rdsoWebinar  On Steel  Melting IIF of steel for rdso
Webinar On Steel Melting IIF of steel for rdso
KapilParyani3
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete ColumnsAxial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Axial Capacity Estimation of FRP-strengthened Corroded Concrete Columns
Journal of Soft Computing in Civil Engineering
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
ANFIS Models with Subtractive Clustering and Fuzzy C-Mean Clustering Techniqu...
ANFIS Models with Subtractive Clustering and Fuzzy C-Mean Clustering Techniqu...ANFIS Models with Subtractive Clustering and Fuzzy C-Mean Clustering Techniqu...
ANFIS Models with Subtractive Clustering and Fuzzy C-Mean Clustering Techniqu...
Journal of Soft Computing in Civil Engineering
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
FISICA ESTATICA DESING LOADS CAPITULO 2.
FISICA ESTATICA DESING LOADS CAPITULO 2.FISICA ESTATICA DESING LOADS CAPITULO 2.
FISICA ESTATICA DESING LOADS CAPITULO 2.
maldonadocesarmanuel
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
ijccmsjournal
 
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra OpticaPruebas y Solucion de problemas empresariales en redes de Fibra Optica
Pruebas y Solucion de problemas empresariales en redes de Fibra Optica
OmarAlfredoDelCastil
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
BeHappy728244
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Webinar On Steel Melting IIF of steel for rdso
Webinar  On Steel  Melting IIF of steel for rdsoWebinar  On Steel  Melting IIF of steel for rdso
Webinar On Steel Melting IIF of steel for rdso
KapilParyani3
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
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