Python Unit 2
Python Unit 2
Noida
Unit: 2
Course Details
(B Tech 2nd Sem /1st Year)
After you have read and studied this module, you should be ab
to:
• To learn the Object-Oriented Concepts in Python.
• To learn the concept of reusability through
inheritance polymorphism and Introspection tools.
• To impart the knowledge of functional programming.
• To learn the concepts of designing graphical user interfaces.
• To explore the knowledge of standard Python libraries.
• Operators
• Loop
• Method
• Variables
• Class , Objects
• Constructor
After you have read and studied this topic, you should be able to:
• Understand the concept of Object-Oriented Systems.
• Child class is the class that inherits from another class, also calle
derived class.
The old class is referred to as the Super class and the new one is calle
the Sub class.
• Parent Class - Base Class or Super Class
• Child Class - Derived Class or Sub Class
Father
• Home
Parent Class • Money
• Business
Son
Child Class •
•
BMW
Job
• Single Inheritance
• Multi-level Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
class Mobile :
members of Child class
object
Syntax:-
Parent Class
class ParentClassName(object):
members of Parent Class
Child Class
class ChildClassName(ParentClassName):
members of Child Class
Example:- Father
class Father:
members of class Father Parent Class
Son
• We can access Parent Class Variables and Methods using Child Cla
Object
• We can also access Parent Class Variables and Methods using Pare
Class Object
• We can not access Child Class Variables and Methods using Paren
Class Object
Output
• When you add the __init__() function, the child class will no longer inherit
the parent's __init__() function.
• Note: The child's __init__() function overrides the inheritance of the
parent's __init__() function.
7/27/2021 (Programming in Advanced Python) Unit No:2 24
Example of the __init__() Function(CO2)
x = Student(“Abhijit", “Niet")
7/27/2021
x.printname() (Programming in Advanced Python) Unit No:2 25
Daily MCQs
1. What will be the output of below Python code?
class Student:
def __init__(self,name,id):
self.name=name
self.id=id
print(self.id)
std=Student("Simon",1)
std.id=2
print(std.id)
A. 1 1 B. 1 2 C. 2 1 D. 2 2
Answer: B
s = Son( )
s.disp()
7/27/2021 (Programming in Advanced Python) Unit No:2 27
Constructor Overriding(CO2)
2. The child's __init__() function overrides the inheritance of the parent's __init__() function.
A. TRUE
B. FALSE
C. Can be true or false
D. Can not say
Answer: A
3. __________function that will make the child class inherit all the methods and properties from its parent.
A. self
B. __init__()
C. super
D. pass
Answer: C
object
Syntax:- object
class ParentClassName(object):
members of Parent Class Parent Class
Grand Child
class GrandChildClassName(ChildClassName):
members of Grand Child Class
OUTPUT
2. Multiple inheritance leaves room for a derived class to have _______ members.
A. dynamic
B. private
C. public
D. ambiguous
E. none of these
Answer: d
object
Child Class
Syntax:- object
class ParentClassName(object):
members of Parent Class
Parent Class
class ChildClassName1(ParentClassName):
members of Child Class 2 Child Class 1 Child Class 2
class ChildClassName2(ParentClassName):
members of Child Class 2
Father
class Son (Father):
members of class Son Child Class
Son Daughter
OUTPUT
If a class is derived from more than one parent class, then it is calle
multiple inheritance.
object
Syntax:- object
class ParentClassName1(object):
members of Parent Class
Parent 1 Parent 2
class ParentClassName2(object):
members of Parent Class Child
object
class Father (object):
members of class Father Parent Class
Father Mother
OUTPUT
Q1. Predict the output of the following program. Also state which concept of OO
is being implemented?
def sum(x,y,z):
print “sum= ”, x+y+z
def sum(a,b):
print “sum= ”, a+b
sum(10,20)
sum(10,20,30)
Q2. Write a program that uses an area() function for the calculation of area o
triangle or a rectangle or a square. Number of sides (3, 2 or 1) suggest the shape
which the area is to be calculated.
Q3. Give a suitable example using Python code to illustrate single level inheritan
considering COUNTRY to be BASE class and STATE to be derived class.
Q4. What is the difference between Multilevel inheritance and multiple
inheritance? Give suitable examples to illustrate.
Q5. What are the different ways of overriding function call in derived class of
python? Illustrate with example.
Q1.What is the need of object-oriented systems? Explain with the help of clas
and objects.
• Write the name of the base class and the derived classes.
• Write the type of inheritance depicted in the above diagram.
• Class Method
• Concrete method
• Abstract Class
• Instance Method
• MRO & Super()
• Polymorphism
• Method Overriding
• Operators
• Loop
• Method
• Variables
• Class , Objects
• Constructor
After you have read and studied this topic, you should be able to
• Understand the class types and method.
• Instance Methods
– Accessor Methods
– Mutator Methods
• Class Methods
Syntax:- object_name.method_name()
Ex:- realme.show_model()
class Mobile:
def show_model(self):
print(“RealMe X”)
realme = Mobile( )
realme.show_model() Calling Instance Method w/o Argument
realme = Mobile( )
realme.show_model(1000) Calling Method with argument
This method is used to access or read data of the variables. This meth
do not modify the data in the variable. This is also called as getter
method.
class Mobile:
Ex:-
def __init__(self):
def get_value(self): self.model = ‘RealMe X’
def get_result(self): def get_model(self):
def get_name(self): return self.model
def get_id(self):
realme = Mobile( )
m = realme.get_model()
print(m)
7/27/2021 (Programming in Advanced Python) Unit No:2 67
Mutator Method(CO2)
This method is used to access or read and modify data of the variable
This method modify the data in the variable. This is also called as set
method.
class Mobile: class Mobile:
Ex:-
def __init__(self):
def set_value(self): self.model = def set_model(self,
def set_result(self): ‘RealMe X’ m):
def set_name(self): self.model = m
def set_id(self): def set_model(self):
self.model = realme = Mobile( )
‘RealMe 2’ realme.set_model(‘Real
realme = Mobile( ) Me X’)
realme.set_model()
7/27/2021 (Programming in Advanced Python) Unit No:2 68
Class Methods(CO2)
Class methods are the methods which act upon the class variables or
static variable of the class.
Decorator @classmethod need to write above the class method.
By default, the first parameter of class method is cls which refers to the class itse
Syntax:-
Decorator
@classmethod
def method_name(cls):
Class Method without Parameter/Formal Arguments
method body
Decorator
@classmethod
def method_name(cls, f1, f2): Class Method with Parameter/Formal Arguments
method body
7/27/2021 (Programming in Advanced Python) Unit No:2 69
Class Method without Parameter(CO2)
Syntax:- Classname.method_name()
class Mobile:
@classmethod
def show_model(cls):
print(“RealMe X”)
class Mobile:
Class Variable
fp = ‘Yes’
Defining Method with parameter
Decorator
@classmethod
def show_model(cls, r):
cls.ram = r
print(cls.fp, cls.ram)
realme = Mobile( )
Syntax:- Classname.method_name(Actual_argument)
Ex:- Mobile.show_model(‘4GB’)
class Mobile:
fp = ‘Yes’
@classmethod
def show_model(cls, r):
cls.ram = r
print(cls.fp, cls.ram)
realme = Mobile( )
Mobile.show_model(101) Calling Method with argument
7/27/2021 (Programming in Advanced Python) Unit No:2 74
Static Methods(CO2)
• Static Methods are used when some processing is related to the class but does
need the class or its instances to perform any work.
• We use static method when we want to pass some values from outside
perform some action in the method.
print(Mobile.fp)
realme = Mobile( )
realme = Mobile( )
Syntax:- Classname.method_name()
class Mobile:
@staticmethod
def show_model():
print(“RealMe X”)
realme = Mobile( )
Mobile.show_model() Calling Static Method w/o Argument
class Mobile:
Decorator @staticmethod Defining Method with parameter
Syntax:- Classname.method_name(Actual_argument)
Ex:- Mobile.show_model(1000)
class Mobile:
@staticmethod
def show_model(m, p):
model = m
price = p
print(model, price)
realme = Mobile( )
Mobile.show_model(‘RealMe X’, 1000) Calling Method with argument
OUTPUT
We use abstract class when there are some common feature shared by
all the objects as they are.
Defence Force Gun is the common feature
Gun = AK 47
Area = shared by all Forces but area
is different for them.
Python also has a super() function that will make the child
class inherit all the methods and properties from its parent.
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
By using the super() function, you do not have to use the nam
of the parent element, it will automatically inherit the metho
and properties from its parent.
7/27/2021 (Programming in Advanced Python) Unit No:2 92
Use the super() Function(CO2)
1. __________function that will make the child class inherit all the methods and properties from its parent.
A. self
B. __init__()
C. super
D. pass
Answer: C
• Method Overriding
• Method Overloading
• Operator Overloading
• You can’t override a method within the same class. It means you ha
to do it in the child class using the Inheritance concept.
Output:
Output:
class Add:
def result(self, a, b):
print(“Addition:”, a+b)
class Multi(Add):
def result(self, a, b):
print(“Multiplication:”, a*b)
m = Multi()
m.result(10, 20)
7/27/2021 (Programming in Advanced Python) Unit No:2 101
Method with super( ) Method(CO2)
• If we write method in the both classes, parent class and child cla
then the parent class’s method is not available to the child class.
• In this case only child class’s method is accessible which mea
child class’s method is replacing parent class’s method.
r = B()
r.rk()
(b) Polymorphism
Q2. Explain method overriding with suitable example.
Q3. What is method resolution operator? Support your answer with suitable
example.
Q4. Explain the concept of polymorphism by giving suitable examples.
Q5. Explain calling the parent's class method inside the overridden method .
• Loop
• Method
• Variables
• Class , Objects
• Constructor
After you have read and studied this topic, you should be able to:
• Understand Introspection using python.
Function Description
help() It is used to find what other functions do.
hasattr() Checks if an object has an attribute.
getattr() Returns the contents of an attribute if there are some.
repr() Return the string representation of object.
callable() Checks if an object has a callable object or not.
Issubclass() Checks if a specific class is a derived class of another
class.
Isinstance() Checks if an object is an instance of a specific class.
sys() Give access to system specific variables and functions.
o/p---True
• This is a small tool that we are going to create and the main u
case of this tool is to help us identify a different aspect of th
objects with respect to its type, methods, attributes, an
documentation.
– https://www.python-course.eu/python3_inheritance.php
– https://www.youtube.com/watch?v=u9x475OGj_U
– https://www.youtube.com/watch?v=byHcYRpMgI4
– https://www.youtube.com/watch?v=FsAPt_9Bf3U
(2) Peter Morgan, Data Analysis from Scratch with Python, AI Sciences
(3) Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, 2nd
edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016
(4) Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 201
7/27/2021 (Programming in Advanced Python) Unit No:2 143
SUMMARY