This page contains the CBSE Computer Science with Python class 12 Unit-1 chapter 4 Inheritance. You can find the solutions for chapter 4 of CBSE class 12 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 12 Computer Science with Python related topic Inheritance questions and answers for the Exercise.
Exercise
Question 1
1. Define the term inheritance.
Answer 1
Inheritance is an OOP feature in which a new class (derived/child class) acquires
the properties (data members) and behaviours (methods) of an existing
class (base/parent class). This helps in reusability and reduces duplicate code.
the properties (data members) and behaviours (methods) of an existing
class (base/parent class). This helps in reusability and reduces duplicate code.
Question 2
2. Give one example for abstract method.
Answer 2
An abstract method is a method that is declared but not fully implemented in the
base class, and it is meant to be implemented in the derived class.
base class, and it is meant to be implemented in the derived class.
Example (real-life):
In a base class
So, derived classes like
Shape, a method area() can be abstract because different shapes calculate area differently.So, derived classes like
Rectangle and Circle implement area() in their own way.Question 3
3. What is single inheritance?
Answer 3
Single inheritance is a type of inheritance in which a derived (child) class is
created from only one base (parent) class.
created from only one base (parent) class.
This means the child class can reuse the data members and methods of that one parent class, and it can also
add new features of its own.
add new features of its own.
Example:
If
details like name, age from
marks.
Person is a base class and Student is derived from it, then Student will inherit commondetails like name, age from
Person and can add extra details like roll number,marks.
Question 4
4. What is multiple inheritance? Explain with an example.
Answer 4
Multiple inheritance is a type of inheritance in which a single derived (child)
class inherits from more than one base (parent) class.
class inherits from more than one base (parent) class.
So, the derived class can get (inherit) the features (data members and methods) of two or
more classes and combine them in one place. This helps in reusability when we need features from different
classes together.
more classes and combine them in one place. This helps in reusability when we need features from different
classes together.
Example:
If we have two base classes
Trainer and Learner, then we can create a derived class Institute(Trainer, Learner).Here,
Institute can use the features of both Trainer (like trainer name/id) and Learner (like learner name/id).Question 5
5. Give one example of multilevel inheritance.
Answer 5
Multilevel inheritance is a type of inheritance in which a class is derived from another derived class,
forming a chain of inheritance (levels).
forming a chain of inheritance (levels).
So, the last class in the chain can inherit features from all the classes above it.
Example:
Person → Student → Graduate Student•
Student inherits common details from Person (like name, age).•
GraduateStudent inherits everything from Student and also indirectly from Person,and can add extra details like stream or specialization.
Question 6
6. Based on the above diagram, answer the following:
(i)
Write the name of the base class and derived class of
State.(ii)
Write the type of inheritance depicted in the diagram.
Answer 6
(i) Write the name of the base class and derived class of State.
•
Base class of
State: Country•
Derived class of
State: City(ii) Write the type of inheritance depicted.
•
It is
Multilevel inheritance (Country → State → City).Question 7
7. Based on the above diagram, answer the following:
(i)
Write the name of the base class and derived classes.
(ii)
Write the type of inheritance depicted in the abovediagram.
Answer 7
(i) Write the name of the base class and derived classes.
•
Base class:
Furniture•
Derived classes:
Sofa, Cot(ii) Write the type of inheritance depicted.
•
It is Hierarchical inheritance (one base class, many derived classes).
Question 8
8. Based on the above diagram, answer the following:
(i)
Write the name of the base classes and derived class.
(ii)
Name the type of inheritance depicted in the above example.
Answer 8
(i) Write the name of the base classes and derived class.
•
Base classes:
Pillow, Bed sheet•
Derived class:
Cot(ii) Name the type of inheritance depicted.
•
It is Multiple inheritance (one child, multiple parents).
Question 9
9. Explain the significance of
super() function.Answer 9
The
super() function is used in inheritance to call a method of the base (parent) class from the derived (child) class.The most common use is calling the base class
__init__() so parent data members are initialized correctly.Why it is important:
•
It helps the derived class reuse the base class code instead of rewriting it.
•
It makes the code cleaner, because we don’t have to write the base class name again and again.
•
In case of multiple inheritance, it is helpful because it follows the correct method search order
(MRO) when classes are written properly (new-style classes).
(MRO) when classes are written properly (new-style classes).
Program (Python 2):
class Person(object):
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, roll):
# calls Person.__init__
super(Student, self).__init__(name)
self.roll = roll
s1 = Student("Mona", 12)
print "Name:", s1.name
print "Roll:", s1.roll
Sample Output:
Name: Mona
Roll: 12
Question 10
10. What are abstract methods?
Answer 10
Abstract methods are those methods which are declared in the base (parent) class but are not fully implemented there. They act like a rule/compulsion for the derived (child) class, meaning the derived class is expected to implement (override) that method in its own way.
Why they are used (importance):
•
Different child classes may perform the same action in different ways, so the base class only defines the method name and purpose.
•
It helps in maintaining a common structure in all derived classes.
Example (simple idea):
If we have a base class
Shape, an abstract method like area() can be declared in it.Then derived classes like
Rectangle and Circle will implement area() differently (because formulas are different).Question 11
11. Explain the concept of overriding methods.
Answer 11
Method overriding means that a derived (child) class writes its own version of a method that is already present in the base (parent) class. The method in the child class has the same name (and generally the same arguments), but its working/implementation is different.
Main point:
When we call the method using an object of the derived class, Python executes the derived class method (because it overrides the base class method).
Why method overriding is useful:
•
It allows the child class to modify or improve the behaviour of the parent class method.
•
It helps us achieve polymorphism (same method name, different behaviour for different classes).
Example:
# Base class
class Furniture(object):
def show(self):
print "This is Furniture"
# Derived class overriding the same method
class Sofa(Furniture):
def show(self):
print "This is Sofa (a type of Furniture)"
s = Sofa()
s.show()
Sample Output:
This is Sofa (a type of Furniture)
Here,
show() is present in both classes, but the Sofa class has its own show() method, so the base method is overridden.Question 12
12. Explain multiple inheritance with the help of an example.
Answer 12
Multiple inheritance is a type of inheritance in which a single derived (child) class inherits from more than one base (parent) class.
So, the child class can use the data members and methods of all the base classes. This helps in reusability when we want to combine features of different classes into one class.
Example:
school(student, Teacher)In this example, the class
school is derived from both student and Teacher.•
student class may store details like id, name.•
Teacher class may store details like teacher id, teacher name, subject.•
The derived class
school(student, Teacher) can access features of both classes.General syntax shown in the book:
class SubClassName(Base1, Base2, Base3):
pass
Important point:
If both base classes have methods with the same name (like
getName()), Python checks them in depth-first, left-to-right order to decide which one will be called.Question 13
13. How do we implement abstract method in Python? Support your answer with an example.
Answer 13
In Python, an abstract method can be implemented in a simple way by:
1.
Writing a method in the base class that only shows a message like “This method should be implemented in the derived class”, and does not do the actual work.
2.
Then, in the derived class, we override that method and write the real logic.
This way, the base class acts like a common structure, and the child class provides the actual implementation.
Example:
# Base class (acts like an abstract class)
class Shape(object):
def area(self):
# Abstract-like method: only a message (no actual formula here)
print "area() should be implemented in the derived class"
# Derived class 1
class Rectangle(Shape):
def __init__(self, l, b):
self.l = l
self.b = b
# overriding the abstract-like method
def area(self):
return self.l * self.b
# Derived class 2
class Circle(Shape):
def __init__(self, r):
self.r = r
# overriding the abstract-like method
def area(self):
pi = 22.0 / 7.0
return pi * self.r * self.r
# ---- main part ----
r1 = Rectangle(10, 5)
print "Area of Rectangle:", r1.area()
c1 = Circle(7)
print "Area of Circle:", c1.area()
Sample Output:
Area of Rectangle: 50
Area of Circle: 154.0
Here,
area() is present in the base class but the actual working is written in the derived classes. This is how we can implement the idea of an abstract method in Python in a simple exam-friendly way.Question 14
14. Find the output of the following code and write the type of inheritance:
(a)
class person(object):
def __init__(self,name,age):self.name=nameself.age=age
def display1(self):print "Name :",self.nameprint "Age :",self.ageclass student(person):def __init__(self,name,age,rollno,marks):super(student,self).__init__(name,age)self.rollno=rollnoself.marks=marksdef display(self):self.display1()print " Roll No:",self.rollnoprint " Marks :",self.marksp=student('Mona',20,12,99)p.display()(b)
class person(object):def __init__(self,name,age):self.name=nameself.age=agedef display1(self):print "Name :",self.nameprint "Age :",self.ageclass student(person):def __init__(self,name,age,rollno,marks):super(student,self).__init__(name,age)self.rollno=rollnoself.marks=marksdef display(self):self.display1()print " Roll No:",self.rollnoprint " Marks :",self.marksclass Gstudent(student):def __init__(self,name,age,rollno,marks,stream):super(Gstudent,self).__init__(name,age,rollno,marks)self.stream=streamdef display2(self):self.display()print " stream:",self.streamp=Gstudent('Mona',20,12,99,'computer')p.display2()(c)
class person(object):def __init__(self,name,age):self.name=nameself.age=agedef display1(self):print "Name :",self.nameprint "Age :",self.ageclass student(object):def __init__(self,rollno,marks):self.rollno=rollnoself.marks=marksdef display(self):print " Roll No:",self.rollnoprint " Marks :",self.marksclass Gstudent(person,student):def __init__(self,name,age,rollno,marks,stream):super(Gstudent,self).__init__(self,stream)person.__init__(self,name,age)student.__init__(self,rollno,marks)self.stream=streamdef display2(self):self.display1()self.display()print " stream:",self.streamp=Gstudent('Mona',20,12,99,'computer')p.display2()Answer 14
14(a) Output + Type (student inherits person)
Output:
Name : Mona
Age : 20
Roll No: 12
Marks : 99
Type of inheritance:Single inheritance
14(b) Output + Type (person → student → Gstudent)
Output:
Name : Mona
Age : 20
Roll No: 12
Marks : 99
stream: computer
Type of inheritance:Multilevel inheritance
14(c) Output + Type (Gstudent inherits person and student)
Output:
Name : Mona
Age : 20
Roll No: 12
Marks : 99
stream: computer
Type of inheritance:Multiple inheritance
Question 15
15. Rewrite the following code after removing errors. Underline each correction and write the output after correcting the code:
class First():def __init__(self):print "first":class Second(object):def __init__(self):print "second"class Third(First, Second):def __init__(self):First.__init__(self):Second.__init__(self):print "that's it"t=Third()t=Third()Answer 15
Corrected code (Python 2)
# Q15 - Corrected program (Python 2)
class First(object): # corrected: added (object)
def __init__(self):
print "first" # corrected: removed colon
class Second(object):
def __init__(self):
print "second"
class Third(First, Second): # corrected: class Third moved out of class Second
def __init__(self):
First.__init__(self) # removed colon at the end
Second.__init__(self) # removed colon at the end
print "that's it"
t = Third() # corrected: removed duplicate assignment
Output
# output
first
second
that's it
Question 16
16. Complete the following code:
class employee(object):def __init__(self,no,name,age):self.no=noself.name= # complete the statementself.age= # complete the statementdef printval(self):print "Number:",self.noprint "Name :",self.nameprint "Age :",self.ageclass pay(object):def __init__(self,dept,salary): # complete the definitiondef display(self): # complete the definition # call printval() # print dept # print salaryAnswer 16
# Q16 - Completed code (Python 2)
class employee(object):
def __init__(self, no, name, age):
self.no = no
self.name = name # corrected: completed self.name assignment
self.age = age # corrected: completed self.age assignment
def printval(self):
print "Number:", self.no
print "Name :", self.name
print "Age :", self.age
class pay(employee):
def __init__(self, dept, salary):
self.dept = dept # corrected: completed dept assignment
self.salary = salary # corrected: completed salary assignment
def display(self):
self.printval() # call printval()
print self.dept # print dept
print self.salary # print salary
# sample run
p1 = pay("Accounts", 45000)
p1.no = 101; p1.name = "Ravi"; p1.age = 35
p1.display()
Sample Output
# output
Number: 101
Name : Ravi
Age : 35
Dept : Accounts
Salary: 45000
Question 17
17. Define a class
furniture in Python with the given specifications:Instance variables:
•
Type
•
Model
Methods
getType()
To return instatnce variable Type
getModel()
To return instance variable Model
show()
To print instance variable Type and Model
Define a class sofa:
•
No_of_seats
•
Cost
Methods
getSeats()
To return instance variable No_of_seats
getCost()
To return instance variable Cost
show()
To print instance variable No_of_seats and Cost
This class inherits class furniture
Answer 17
# Q17 - Furniture / Sofa (Python 2)
class Furniture(object):
Type = None
Model = None
def __init__(self, Type, Model):
self.Type = Type
self.Model = Model
def getType(self):
return self.Type
def getModel(self):
return self.Model
def show(self):
print "Type :", self.Type
print "Model:", self.Model
class Sofa(Furniture):
No_of_seats = None
Cost = None
def __init__(self, Type, Model, No_of_seats, Cost):
Furniture.__init__(self, Type, Model)
self.No_of_seats = No_of_seats
self.Cost = Cost
def getSeats(self):
return self.No_of_seats
def getCost(self):
return self.Cost
# overriding show()
def show(self):
Furniture.show(self)
print "Seats:", self.No_of_seats
print "Cost :", self.Cost
Type = raw_input("Enter furniture type: ")
Model = raw_input("Enter model: ")
No_of_seats = int(raw_input("Enter number of seats: "))
Cost = int(raw_input("Enter cost: "))
sofa_obj = Sofa(Type, Model, No_of_seats, Cost)
print "\nFurniture Details:"
sofa_obj.show()
Sample Output
# output (sample)
Enter furniture type: Sofa
Enter model: S123
Enter number of seats: 3
Enter cost: 25000
Furniture Details:
Type : Sofa
Model: S123
Seats: 3
Cost : 25000
Question 18
18. 1. Define a class trainer in Python with the given specifications:
Instance variables:
•
Name
•
T_ID
Methods
getName()
To print instance variable Name
getT_ID()
To print instance variable T_ID
Define a class learner in Python with teh given specifications:
Instance variables:
•
L_Name
•
L_ID
Methods
getName()
To print instance variable L_Name
getLID()
To print instance variable L_ID
Define a class Institute in Python with the given specifications:
Instance variables:
•
I_Name
•
I_Code
Methods
getName()
To print instance variable I_Name
getCode()
To print instance variable I_Code
The class Institute inherits the class Trainer and Learner
Answer 18
# Q18 - Multiple inheritance (Python 2)
class Trainer(object):
Name = None
T_ID = None
def __init__(self, Name, T_ID):
self.Name = Name
self.T_ID = T_ID
def getName(self):
print "Name :", self.Name
def getT_ID(self):
print "T_ID :", self.T_ID
class Learner(object):
L_Name = None
L_ID = None
def __init__(self, L_Name, L_ID):
self.L_Name = L_Name
self.L_ID = L_ID
def getName(self):
print "L_Name:", self.L_Name
def getLID(self):
print "L_ID :", self.L_ID
class Institute(Trainer, Learner):
I_Name = None
I_Code = None
def __init__(self, Name, T_ID, L_Name, L_ID, I_Name, I_Code):
Trainer.__init__(self, Name, T_ID)
Learner.__init__(self, L_Name, L_ID)
self.I_Name = I_Name
self.I_Code = I_Code
# as asked in question: getName() prints I_Name
def getName(self):
print "I_Name:", self.I_Name
def getCode(self):
print "I_Code:", self.I_Code
Name = raw_input("Enter trainer name: ")
T_ID = raw_input("Enter trainer id: ")
L_Name = raw_input("Enter learner name: ")
L_ID = raw_input("Enter learner id: ")
I_Name = raw_input("Enter institute name: ")
I_Code = raw_input("Enter institute code: ")
obj = Institute(Name, T_ID, L_Name, L_ID, I_Name, I_Code)
print "\nDetails:"
Trainer.getName(obj)
obj.getT_ID()
Learner.getName(obj)
obj.getLID()
obj.getName()
obj.getCode()
Sample Output
# output (sample)
Enter trainer name: Arun
Enter trainer id: T01
Enter learner name: Bala
Enter learner id: L55
Enter institute name: ABC Institute
Enter institute code: I100
Details:
Name : Arun
T_ID : T01
L_Name: Bala
L_ID : L55
I_Name: ABC Institute
I_Code: I100
Question 19
19. Define a class student in Python with the given specifications:
Instance Variables:
Roll number, name
•
Name
•
T_ID
Methods
Getdata()
– To input roll number and name
Printdata()
– To display roll number and name
Define another class marks, which is derived from student class
Instance variable
Markes in five subjects
Methods:
Inputdata()
– To call Getdata() and input 5 subjects marks.
Outdata()
– To call printdata() and to display 5 subjects marks.
Implement the above program in Python.
Answer 19
# Q19 - Student / Marks (Python 2)
class student(object):
Roll_No = None
Name = None
def Getdata(self):
self.Roll_No = int(raw_input("Enter roll number: "))
self.Name = raw_input("Enter name: ")
def Printdata(self):
print "Roll number:", self.Roll_No
print "Name :", self.Name
class marks(student):
Marks = None
def Inputdata(self):
student.Getdata(self)
self.Marks = []
i = 1
while i <= 5:
Mark = int(raw_input("Enter marks in subject " + str(i) + ": "))
self.Marks.append(Mark)
i = i + 1
def Outdata(self):
student.Printdata(self)
print "Marks (5 subjects):", self.Marks
obj = marks()
obj.Inputdata()
print "\nDetails:"
obj.Outdata()
Sample Output
# output (sample)
Enter roll number: 12
Enter name: Mona
Enter marks in subject 1: 78
Enter marks in subject 2: 80
Enter marks in subject 3: 74
Enter marks in subject 4: 90
Enter marks in subject 5: 88
Details:
Roll number: 12
Name : Mona
Marks (5 subjects): [78, 80, 74, 90, 88]
Question 20
20. Define a class
employee in Python with the given specifications:Instance variables:
Employee number, name
Methods:
Getdata()
– To input employee number and name
Printdata()
– To display employee number and name
Define another class Teaching, which is derived from employee
Instance variable
Department name
Methods:
Inputdata()
– To call Getdata() and input department name.
Outdata()
– To call printdata() and to display department name.
Define another class Non_teaching, which is derived from employee
Instance variable
Designation
Methods:
Inputdata()
– To call Getdata() and input designation.
Outdata()
– To call printdata() and to display designation.
Implement the above program in python.
Answer 20
# Q20 - Hierarchical inheritance (Python 2) with file storage
class employee(object):
eno = None
name = None
def Getdata(self):
self.eno = raw_input("Enter employee number: ")
self.name = raw_input("Enter employee name: ")
def Printdata(self):
print "Employee No :", self.eno
print "Employee Name:", self.name
class Teaching(employee):
dept = None
def Inputdata(self):
employee.Getdata(self)
self.dept = raw_input("Enter department name: ")
def Outdata(self):
employee.Printdata(self)
print "Department :", self.dept
class Non_teaching(employee):
desig = None
def Inputdata(self):
employee.Getdata(self)
self.desig = raw_input("Enter designation: ")
def Outdata(self):
employee.Printdata(self)
print "Designation :", self.desig
# --- store one teaching + one non-teaching ---
t = Teaching()
t.Inputdata()
n = Non_teaching()
n.Inputdata()
f = open("emp20.txt", "w")
f.write("T|" + t.eno + "|" + t.name + "|" + t.dept + "\n")
f.write("N|" + n.eno + "|" + n.name + "|" + n.desig + "\n")
f.close()
print "\n# output (from file)"
f = open("emp20.txt", "r")
for line in f:
parts = line.strip().split("|")
if parts[0] == "T":
obj = Teaching()
obj.eno = parts[1]; obj.name = parts[2]; obj.dept = parts[3]
obj.Outdata()
else:
obj = Non_teaching()
obj.eno = parts[1]; obj.name = parts[2]; obj.desig = parts[3]
obj.Outdata()
print "----"
f.close()
Sample Output
# output (sample)
Employee No : 201
Employee Name: Riya
Department : Physics
----
Employee No : 305
Employee Name: Sameer
Designation : Clerk
----
Question 21
21. Define a class employee in Python with the given specifications:
Instance variables:
Employee number, name
Methods:
Getdata()
– To input employee number and name
Printdata()
– To display employee number and name
Define another class payroll, which is derived from employee
Instance variable
Salary
Computer Science
Methods:
Inputdata()
– To call Getdata() and input salary.
Outdata()
– To call printdata() and to display salary.
Define another class leave, which is derived from payroll.
Instance variable
No of days
Methods:
acceptdata()
– To call Inputdata() and input no of days.
showdata()
– To call Outdata() and to display no of days.
Implement the above program in python.
Answer 21
# Q21 - Multilevel inheritance (Python 2)
class employee(object):
Employee_number = None
name = None
def Getdata(self):
self.Employee_number = raw_input("Enter employee number: ")
self.name = raw_input("Enter employee name: ")
def Printdata(self):
print "Employee No :", self.Employee_number
print "Employee Name:", self.name
class payroll(employee):
Salary = None
def Inputdata(self):
employee.Getdata(self)
self.Salary = int(raw_input("Enter salary: "))
def Outdata(self):
employee.Printdata(self)
print "Salary :", self.Salary
class leave(payroll):
No_of_days = None
def acceptdata(self):
payroll.Inputdata(self)
self.No_of_days = int(raw_input("Enter no of days: "))
def showdata(self):
payroll.Outdata(self)
print "No of days :", self.No_of_days
obj = leave()
obj.acceptdata()
print "\nDetails:"
obj.showdata()
Sample Output
# output (sample)
Enter employee number: 501
Enter employee name: Kiran
Enter salary: 60000
Enter no of days: 3
Details:
Employee No : 501
Employee Name: Kiran
Salary : 60000
No of days : 3
Question 22
22. Payroll information system:
a.
Declare the base class ’employee’ with employee’s number, name, designation, address, phone number.
b.
Define and declare the function getdata() and putdata() to get the employee’s details and print employee’s details.
c.
Declare the derived class salary with basic pay, DA, HRA, Gross pay, PF, Income tax and Net pay.
d.
Declare and define the function getdata1() to call getdata() and get the basic pay,
e.
Define the function calculate() to find the net pay.
f.
Define the function display() to call putdata() and display salary details .
g.
Create the derived class object.
h.
Read the number of employees.
i.
Call the function getdata1() and calculate() to each employees.
j.
Call the display() function.
Answer 22
# Q22 - Payroll system (Python 2)
# Note: DA, HRA, PF and Income_tax are entered as direct values.
# step a: Declare base class employee with required employee details.
class employee(object):
employee_number = None
name = None
designation = None
address = None
phone_number = None
# step b: Define getdata() to read employee details.
def getdata(self):
self.employee_number = raw_input("Employee number: ")
self.name = raw_input("Name: ")
self.designation = raw_input("Designation: ")
self.address = raw_input("Address: ")
self.phone_number = raw_input("Phone number: ")
# step b: Define putdata() to print employee details.
def putdata(self):
print "Employee number:", self.employee_number
print "Name :", self.name
print "Designation:", self.designation
print "Address:", self.address
print "Phone number:", self.phone_number
# step c: Declare derived class salary with salary-related members.
class salary(employee):
basic_pay = None
DA = None
HRA = None
Gross_pay = None
PF = None
Income_tax = None
Net_pay = None
# step d: Define getdata1() to call getdata() and read basic pay and allowances.
def getdata1(self):
employee.getdata(self)
self.basic_pay = float(raw_input("Basic pay: "))
self.DA = float(raw_input("DA: "))
self.HRA = float(raw_input("HRA: "))
self.PF = float(raw_input("PF: "))
self.Income_tax = float(raw_input("Income tax: "))
# step e: Define calculate() to find net pay.
def calculate(self):
self.Gross_pay = self.basic_pay + self.DA + self.HRA
self.Net_pay = self.Gross_pay - (self.PF + self.Income_tax)
# step f: Define display() to call putdata() and show salary details.
def display(self):
employee.putdata(self)
print "Basic pay :", self.basic_pay
print "DA :", self.DA
print "HRA :", self.HRA
print "Gross pay :", self.Gross_pay
print "PF :", self.PF
print "Income tax:", self.Income_tax
print "Net pay :", self.Net_pay
# step h: Read the number of employees.
n = int(raw_input("Enter number of employees: "))
i = 1
while i <= n:
print "\nEnter details for employee", i
# step g: Create the derived class object.
s = salary()
# step i: Call getdata1() and calculate() for each employee.
s.getdata1()
s.calculate()
print "\nEmployee details:"
# step j: Call display() function.
s.display()
print "----"
i = i + 1
Sample Output
# output (sample)
Enter number of employees: 1
Enter details for employee 1
Employee details:
Number: 101
Name : Riya
Designation: Teacher
Addr : Chennai
Phone: 9876543210
Basic pay : 50000.0
DA : 5000.0
HRA : 3000.0
Gross pay : 58000.0
PF : 2000.0
Income tax: 2500.0
Net pay : 53500.0
----
Question 23
23. Railway reservation system:
a.
Declare the base class Train with train number, name, Starting station, destination, departure time,arrival time, etc.
b.
Define and declare the function getdata() and putdata() to get the train details and print the details.
c.
Define search() function to search train detail using train number.
d.
Declare the derived class passenger with ticket number, PNR name of the passenger, gender, age, address, phone number, etc.
e.
Declare and define the function getdata1() to call search() function to get the train details and get the passenger’s information.
f.
Define the function display() to call putdata() and display passenger’s details.
g.
Create base class object.
h.
Read the number of trains.
i.
Create the derived class object.
j.
Read the number of passengers.
k.
Call the function getdata1() to each passenger.
l.
Call the display() function.
Answer 23
# Q23 - Railway reservation (Python 2) with file storage
# step a: Declare base class Train with train details.
class Train(object):
train_number = None
name = None
Starting_station = None
destination = None
departure_time = None
arrival_time = None
# step b: Define getdata() to read train details.
def getdata(self):
self.train_number = raw_input("Train number: ")
self.name = raw_input("Train name: ")
self.Starting_station = raw_input("Starting station: ")
self.destination = raw_input("Destination: ")
self.departure_time = raw_input("Departure time: ")
self.arrival_time = raw_input("Arrival time: ")
# step b: Define putdata() to display train details.
def putdata(self):
print "Train No :", self.train_number
print "Name :", self.name
print "From :", self.Starting_station
print "To :", self.destination
print "Dep Time :", self.departure_time
print "Arr Time :", self.arrival_time
# step c: Define search() function to search train by train number.
def search_train(trains, train_number):
for t in trains:
if t.train_number == train_number:
return t
return None
# step d: Declare derived class passenger with passenger details.
class passenger(Train):
ticket_number = None
PNR = None
passenger_name = None
gender = None
age = None
address = None
phone_number = None
# step e: Define getdata1() to call search and get passenger details.
def getdata1(self, trains):
self.ticket_number = raw_input("Ticket number: ")
self.PNR = raw_input("PNR: ")
self.passenger_name = raw_input("Passenger name: ")
self.gender = raw_input("Gender: ")
self.age = raw_input("Age: ")
self.address = raw_input("Address: ")
self.phone_number = raw_input("Phone number: ")
self.train_number = raw_input("Enter train number to book: ")
t = search_train(trains, self.train_number)
self.train_obj = t
# step f: Define display() to show passenger and booked train details.
def display(self):
print "\nPassenger Details"
print "Ticket:", self.ticket_number
print "PNR :", self.PNR
print "Name :", self.passenger_name
print "Gender:", self.gender
print "Age :", self.age
print "Address:", self.address
print "Phone :", self.phone_number
print "\nBooked Train Details"
if self.train_obj is None:
print "Train not found!"
else:
self.train_obj.putdata()
# step h: Read the number of trains.
nt = int(raw_input("Enter number of trains: "))
trains = []
i = 1
while i <= nt:
print "\nEnter train", i
# step g: Create base class object.
t = Train()
t.getdata()
trains.append(t)
i = i + 1
# store trains
f = open("trains23.txt", "w")
for t in trains:
f.write(t.train_number + "|" + t.name + "|" + t.Starting_station + "|" + t.destination + "|" + t.departure_time + "|" + t.arrival_time + "\n")
f.close()
# step j: Read the number of passengers.
np = int(raw_input("\nEnter number of passengers: "))
fp = open("passengers23.txt", "w")
i = 1
while i <= np:
print "\nEnter passenger", i
# step i: Create the derived class object.
p = passenger()
# step k: Call getdata1() for each passenger.
p.getdata1(trains)
# store passenger booking
fp.write(p.ticket_number + "|" + p.PNR + "|" + p.passenger_name + "|" + p.train_number + "\n")
# step l: Call the display() function.
p.display()
i = i + 1
fp.close()
print "\n# output (bookings saved to file passengers23.txt)"
Sample Output
# output (sample)
Passenger Details
Ticket: TK01
PNR : PNR100
Name : Mona
Booked Train Details
Train No : 12001
Name : Express
From : Chennai
To : Delhi
Dep Time : 10:00
Arr Time : 06:00
Question 24
24. SKP Hotel offers accommodation, meals facilities.
a.
Create a class Accommodation with Room Number, type of room, and rent, etc..
b.
Create a class meals services includes: meals code, name, price, etc..
c.
Create a class customer with customer number, name, address, etc.
d.
Customer class is derived by using Accommodation and meals classes.
Answer 24
# Q24 - Multiple inheritance (Python 2) with file storage
# step a: Create class Accommodation with Room_Number, type_of_room and rent.
class Accommodation(object):
Room_Number = None
type_of_room = None
rent = None
def set_room(self, Room_Number, type_of_room, rent):
self.Room_Number = Room_Number
self.type_of_room = type_of_room
self.rent = rent
# step b: Create class meals with meals code, name and price.
class meals(object):
meal_code = None
name = None
meal_service_name = None
price = None
def set_meal(self, meal_code, name, price):
self.meal_code = meal_code
self.name = name
self.meal_service_name = name
self.price = price
# step c: Create class customer with customer details.
# step d: Derive customer from Accommodation and meals classes.
class customer(Accommodation, meals):
customer_number = None
name = None
address = None
def set_customer(self, customer_number, name, address):
self.customer_number = customer_number
self.name = name
self.address = address
def display(self):
print "Customer No:", self.customer_number
print "Name :", self.name
print "Address :", self.address
print "Room No :", self.Room_Number
print "Room Type :", self.type_of_room
print "Rent :", self.rent
print "Meal Code :", self.meal_code
print "Meal Name :", self.meal_service_name
print "Meal Price :", self.price
# inputs
customer_number = raw_input("Customer number: ")
name = raw_input("Customer name: ")
addr = raw_input("Address: ")
Room_Number = raw_input("Room number: ")
type_of_room = raw_input("Room type: ")
rent = raw_input("Rent: ")
meal_code = raw_input("Meal code: ")
meal_name = raw_input("Meal name: ")
price = raw_input("Meal price: ")
cust = customer()
cust.set_customer(customer_number, name, addr)
cust.set_room(Room_Number, type_of_room, rent)
cust.set_meal(meal_code, meal_name, price)
# file store
f = open("hotel24.txt", "w")
f.write(customer_number + "|" + cust.name + "|" + addr + "|" + Room_Number + "|" + type_of_room + "|" + rent + "|" + meal_code + "|" + meal_name + "|" + price)
f.close()
print "\n# output (from file)"
f = open("hotel24.txt", "r")
d = f.read().strip().split("|")
f.close()
cust2 = customer()
cust2.set_customer(d[0], d[1], d[2])
cust2.set_room(d[3], d[4], d[5])
cust2.set_meal(d[6], d[7], d[8])
cust2.display()
Sample Output
# output (sample)
Customer No: 11
Name : Riya
Room No : 203
Meal Name : Lunch
Question 25
25. Implement the following using multilevel information.
a.
Create a student class with student number and name.
b.
Class graduate is created by using student.
c.
Graduate class is created using subject code and subject name.
d.
Class Post Graduate is created by using Graduate.
e.
Post Graduate class is created using master subject code and master subject name
Answer 25
# Q25 - Multilevel inheritance (Python 2) with file storage
# step a: Create Student class with student number and name.
class Student(object):
student_number = None
name = None
def get_student(self):
self.student_number = raw_input("Student number: ")
self.name = raw_input("Student name: ")
def show_student(self):
print "Student No :", self.student_number
print "Student Name:", self.name
# step b: Create Graduate class using Student class.
class Graduate(Student):
subject_code = None
subject_name = None
# step c: Use subject code and subject name in Graduate class.
def get_graduate(self):
Student.get_student(self)
self.subject_code = raw_input("Subject code: ")
self.subject_name = raw_input("Subject name: ")
def show_graduate(self):
Student.show_student(self)
print "Subject Code:", self.subject_code
print "Subject Name:", self.subject_name
# step d: Create PostGraduate class using Graduate class.
class PostGraduate(Graduate):
master_subject_code = None
master_subject_name = None
# step e: Use master subject code and master subject name in PostGraduate class.
def get_pg(self):
Graduate.get_graduate(self)
self.master_subject_code = raw_input("Master subject code: ")
self.master_subject_name = raw_input("Master subject name: ")
def show_pg(self):
Graduate.show_graduate(self)
print "Master Code :", self.master_subject_code
print "Master Name :", self.master_subject_name
pg = PostGraduate()
pg.get_pg()
# file store
f = open("student25.txt", "w")
f.write(pg.student_number + "|" + pg.name + "|" + pg.subject_code + "|" + pg.subject_name + "|" + pg.master_subject_code + "|" + pg.master_subject_name)
f.close()
print "\n# output (from file)"
f = open("student25.txt", "r")
d = f.read().strip().split("|")
f.close()
pg2 = PostGraduate()
pg2.student_number = d[0]
pg2.name = d[1]
pg2.subject_code = d[2]
pg2.subject_name = d[3]
pg2.master_subject_code = d[4]
pg2.master_subject_name = d[5]
pg2.show_pg()
Sample Output
# output (sample)
Student No : 12
Student Name: Mona
Subject Code: CS
Subject Name: Computer Science
Master Code : MCS
Master Name : Advanced CS