0% found this document useful (0 votes)
3 views

pythonunit5

The document is a model answer for a Python programming exam, covering various topics such as class definition, method overloading, modules, inheritance, and user-defined packages. It includes code examples and explanations for each concept, demonstrating how to implement them in Python. Additionally, it provides exercises related to creating classes and managing student details.

Uploaded by

becupeli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

pythonunit5

The document is a model answer for a Python programming exam, covering various topics such as class definition, method overloading, modules, inheritance, and user-defined packages. It includes code examples and explanations for each concept, demonstrating how to implement them in Python. Additionally, it provides exercises related to creating classes and managing student details.

Uploaded by

becupeli
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216

Subject Name: Python programming UNIT 5


Model Answer Subject Code: 22616
Q.N. ANSWER MARKING
SCHEME
a Write syntax of defining class in Python.. 2M
ANS class <ClassName>: 2M for
<statement1> UNIT 3 syntax
<statement2>
.
.
<statementN>

b Illustrate with example method over loading. 4M


• Method overloading is the ability to define the method with the same
name but with a different number of arguments and data types. Explanati
• With this ability one method can perform different tasks, depending on on 1 M
the number of arguments or the types of the arguments given. and
• Method overloading is a concept in which a method in a class Example 3
performs operations according to the parameters passed to it. M
Example: With a method to perform different operations using method
overloading. class operation:
def add(self,a,b):
return a+b
op1=operati
on()
# To add two integer numbers
print("Addition of integer
numbers=",op1.add(10,20)) # To add
two floting point numbers
print("Addition of integer
numbers=",op1.add(11.12,12.13)) # To add
two strings
print("Addition of integer
numbers=",op1.add("Hello","Python")) Output:
Addition of integer
numbers= 30 Addition of
integer numbers= 23.25
Addition of integer numbers= HelloPython
Python does not support method overloading, that is, it is not possible to
Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 1
SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
define more than one method with the same name in a class in Python.

This is because method arguments in python do not have a type. A method


accepting one argument can be called with an integer value, a string or a
double as shown in next example.
class Demo:
def method(self, a):
print(a)
obj= Demo()
obj.method(50)
obj.method('Meenakshi')
obj.method(100.2)
Output:
50
Meenakshi
100.2
c Example module. How to define module. 6M
A module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. 2 M for
A module is a Python object with arbitrarily named attributes that you can Explanation
bind
and reference.
Simply, a module is a file consisting of Python code. A module can define 2M for
functions,
classes and variables. A module can also include runnable code. Creating
module
Example
2M for
Using/accseing
The Python code for a module named aname normally resides in a file named
aname.py. Here's an example of a simple module, support.py
def print_func( par ):
print "Hello : ", par
return
To create a module just save the code you want in a file with the file extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule mymodule.greeting("ABC")
d 2M
Design a class student with data members; Name, roll number
address.
Create suitable method for reading and printing students details.

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 2


SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
class Student:
Four-1/2 M For
def getStudentDetails(self): Each
self.rollno=input("Enter Roll
Number : ") self.name =
input("Enter Name : ")

self.address =input("Enter
Address : ")

def printStudentDetails(self):
print(self.rollno,self.name,
self.address)
S1=Student
()

S1.getStud
entDetails()
print("Stud

ent Details
")

S1.printStu
dentDetails

() Output:
Enter Roll
Number :
001 Enter
Name :
ABC
Enter Address :
New York Student
Details :
001 ABC New York
(Any suitable program can consider)

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 3


SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5

e Create a parent class named Animals and a child class Herbivorous 6M


which will extend the class Animal. In the child class Herbivorous over
side the method feed (). Create a object

#parent class
Class Animal:
#properties
multicellular = True
# Eukaryotic means Cells with
Nucleus eukaryotic = True
# functionbreath
Def breathe(self):
Print(“I breath oxygen”)
#function feed
Def feed(self):
Print (“I eat food”)
# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")
herbi = Herbivorous()

#child class
Class Herbivorous(Animal):
herbi.feed()
#calling some other function
Herbi.breathe()

Output:
I eat only plants.iam vegetarian.
I breath oxygen

f Explain method overloading and overriding in python.. 4M

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 4


SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5
Method overloading is used for creating methods with similar functionalities 1M each
but different input parameters.
Method overriding is used for providing a specific implementation of a
method in a subclass.
The choice of which method to invoke is made at compile-time based on the
method signature.

When two or more methods in the same class have the same method
name but different parameters, this is called overloading.
In contrast, overriding occurs when two methods have the same name and
parameters.
You can use Overloading and Overriding more effectively now that you
understand the distinction between the two

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 5


SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5

g Write a program illustrating use of user defined package in python 6M


# calculator.py 2M For Each

def add(a, b):

return a + b

def sub(a, b):

return a - b

def mul(a, b):

return a * b

def div(a, b):

return a / b

# main.py

import calculator

print("Addition of 5 and 4 is:", calculator.add(5, 4))

print("Subtraction of 7 and 2 is:", calculator.sub(7, 2))

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 6


SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5
print("Multiplication of 3 and 4 is:", calculator.mul(3, 4))

print("Division of 12 and 3 is:", calculator.div(12, 3)

output Addition of 5 and 4 is: 9

Subtraction of 7 and 2 is: 5

Multiplication of 3 and 4 is: 12

Division of 12 and 3 is: 4.0

h Write program to implement concept of inheritance in python 6M


# A Python program to demonstrate inheritance 2M For
Definition
# Base or Super class. Note object in bracket.
# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"

class Person(object):

# Constructor

def __init__(self, name):


self.name = name

# To get name
def getName(self):
return self.name

# To check if this person is an employee


def isEmployee(self):
return False
# Inherited or Subclass (Note Person in bracket)
class Employee(Person):

# Here we return true


def isEmployee(self):
return True

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 7


SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5
# Driver code
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2") # An Object of Employee


print(emp.getName(), emp.isEmployee())

output

Output:
Geek1 False
Geek2 True

i Write a program to create class students with roll no and name and 2M
display its contents
# Create class Student

class Student:

def __init__(self, name, roll, s1, s2):

self.name = name

self.roll = roll

self.s1 = s1

self.s2 = s2

# Function to create and append students

def accept(self, Name, Roll, score1, score2):

obj = Student(Name, Roll, score1, score2)

ls.append(obj)

# Display student details

def display(self, obj):

print("Name : ", obj.name)

print("RollNo : ", obj.roll)

print("Score1 : ", obj.s1)

print("Score2 : ", obj.s2)

print("\n")

# Search Function

def search(self, rn):

for i in range(ls.__len__()):

if (ls[i].roll == rn):

return i

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 8


SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5
# Deletion

def delete(self, rn):

i = obj.search(rn)

del ls[i]

# Update Function

def update(self, rn, No):

i = obj.search(rn)

rolln = No

ls[i].roll = rolln;

ls = []

# Object of class

obj1 = Student('', 0, 0, 0)

print("\nOperations used, ")

print("\n1.Accept Student details\n"

"2.Display Student Details\n"

"3.Search Details of a Student\n"

"4.Delete Details of Student"

"\n5.Update Student Details\n6.Exit")

obj1.accept("A", 1, 100, 100)

obj1.accept("B", 2, 90, 90)

obj1.accept("C", 3, 80, 80)

print("\n")

print("\nList of Students\n")

for i in range(ls.__len__()):

obj1.display(ls[i])

print("\n Student Found, ")

s = obj1.search(2)

obj1.display(ls[s])

obj1.delete(2)

print(ls.__len__())

print("List after deletion")

for i in range(ls.__len__()):

obj1.display(ls[i])

obj1.update(3, 2)

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page 9


SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5
print(ls.__len__())

print("List after updation")

for i in range(ls.__len__()):

obj1.display(ls[i])

print("Thank You !")

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page


10
SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5

h Define class and object in python 2m


A class is a code template for creating objects. Objects have member variables and
have behaviour associated with them.
In python a class is created by the keyword class .
An object is created using the constructor of the class.
This object will then be called the instance of the class.

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Clas class Person:

def __init__(self, name, age):

self.name = name

self.age = age

def __str__(self):

return f"{self.name}({self.age})"

p1 = Person("John", 36)

print(p1)s is like an object constructor, or a "blueprint" for creating objects.

Prof. Ghodekar.k.a Shree Ramchandra College of Engineering Page


11
SHREE RAMCHANDRA COLLEGE OF ENGINEERING, LONIKAND, PUNE 412216
UNIT 5

Prof. Ghodekar .k.a Shree Ramchandra College of Engineering Page


12

You might also like