practical workbook object oriented programming · object-oriented programming object-oriented...
TRANSCRIPT
Practical Workbook
Object Oriented Programming
Dept. of Computer & Information Systems Engineering
NED University of Engineering & Technology,
Name _____________________________
Year _____________________________
Batch _____________________________
Roll No _____________________________
Department: __________________________________
Practical Workbook
Object Oriented Programming
Prepared by:
Kashif Asrar
Revised in: February 2019
Dept. of Computer & Information Systems Engineering
NED University of Engineering & Technology,
Introduction
This workbook has been compiled to assist the conduct of practical classes for CS-116 “Object
Oriented Programming”. Practical work relevant to this course aims at introducing the basic as well
as advance concepts of objects oriented programming using Python language such as class, object,
inheritance, multiple inheritance, polymorphism, function and operator overloading.
The Course Profile of CS-116 “Object Oriented Programming” lays down the following Course
Learning Outcome:
CLO-3 Practice computer programming using object oriented paradigm (Lab work).
All lab sessions of this workbook have been designed to assist the achievement of the above CLO. A
rubric to evaluate student performance has been provided at the end of the workbook.
The Workbook is comprised of fourteen labs starting with a practical on the classes and objects
based programming environment and fundamental concepts of Object Oriented programming
language. Next few lab sessions deal with familiarization with constructor and types of methods.
Inheritance: a key concept in all object oriented programming languages is discussed in Lab session
4. Lab Session 5 covers extended version of inheritance i.e. multiple inheritance. Lab session 6
Covers the representation of class i.e. Class Diagram. Lab session 7 introduces the concept of
Method resolution order (MRO) that is applied in case of inheritance when two or more methods
have same name. Lab session 8 introduces abstract classes. Lab session 9 discusses the existing and
implements user defined meta-functions. Polymorphism is discussed in Lab 10. The programming
of exception handling is explained in lab 11. Lab 12 covers concept of function overloading.
Operator overloading is discussed in Lab session 13. The lab 14 discusses the structuring of Projects
with the help of modules and Packages.
This workbook is designed to assist (both) instructor and student, practically realizing theoretical
concepts of the course, and providing in-depth understanding and elaborate system programming
experience.
CONTENTS
Lab Session No. Object Page No.
1 Develop Object and Classes. 1
2 Develop Default and User Defined Constructor. 5
3 Explore Different Types of Methods within a Single Class. 8
4 Construct Classes using Inheritance. 11
5 Construct Classes using Multiple Inheritance. 15
6 Develop Class Diagrams. 19
7 Resolve the Conflicts of Method Accessibility with Method Resolution
Order (MRO). 26
8 Illustrate Use of Abstract Classes. 29
9 Explore Built-in and User-Defined Meta Functions. 33
10 Illustrate Use of Polymorphism. 36
11 Practice Exception Handling. 39
12 Illustrate Function Overloading.
43
13 Illustrate Operator Overloading.
46
14 Explore Structuring of Projects using Modules and Packages. 50
Object Oriented Programming Lab Session 01 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
1
Lab Session 01
OBJECT
Develop Object and Classes.
OBJECT-ORIENTED PROGRAMMING Object-Oriented Programming (OOP) represents an attempt to make programs more closely model the
way people think about and deal with the world. Object-oriented programming is a paradigm in which a
software system is decomposed into subsystems based on objects. Computation is done by objects
exchanging messages among themselves. The paradigm enhances software maintainability, extensibility
and reusability
CLASSES AND OBJECTS Object is the basic unit of object oriented programming. Object represents a Physical/real entity. All real
world objects have three characteristics:
State/Attributes: The states of an object represent all the information held within it
Behavior: Behavior of an object is the set of action that it can perform to change the state of the
object.
Identity: Object is identified by its unique name
Classes are data types based on which objects are created. Objects with similar attributes and methods are
grouped together to form a class. Thus, a class is a logical abstraction, but an object has physical
existence. In other words, an object is an instance of a class.
GENERAL FORMAT
Class class_name:
Variable variable_name
def function_name(self):
**function implementation here**
Object Oriented Programming Lab Session 01 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2
EXCERCISE
1. Develop a „bank‟ class and implement a method „application_for_loan‟ such that it gives two possible
outputs based on the value of variable „loan_take_previously‟ within the class. The two possible
outputs are
a. Loan granted (if loan_taken_previously=false)
b. Loan is not granted(if loan_taken_previously=false)
Also makes two objects of afore mentioned class and modify the value of „loan_taken_previously‟
with the help of object.
Write the program here:
Object Oriented Programming Lab Session 01 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
3
2. Develop a class „complex number‟ that takes real and imaginary part from user separately and print the
complex number in proper format i.e. 3+4j
3. Develop a class „snake‟ that has a method „introduction‟. The method „introduction‟ takes the name,
color, and age of the snake. Make the object of snake class and specify the attributes to „introduction‟
method and print the attributes in same method.
Write the program here:
Write the program here:
Object Oriented Programming Lab Session 01 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
4
4. Develop a class „car‟ that takes the attributes of wheels, miles, make, model, year, sold_on by default.
Develop two methods „sales_price‟ and „purchase_price‟. The „sales_price‟ checks if „sold_on‟ is none
then return price (non-zero value) otherwise return zero value. . The „purchase_price‟ checks if
„sold_on‟ is none then return price (zero value) otherwise return price (non-zero value).
Write the program here:
Object Oriented Programming Lab Session 02 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
5
Lab Session 02
OBJECT
Develop Default and User Defined Constructor.
DEFAULT CONSTRUCTOR The first method __init__() is a special method, which is called class default constructor or initialization
method that Python calls when you create a new instance of this class. The default constructor takes only
one parameter that is the reference of the object. The reference is usually referred as „self‟
GENERAL SYNTAX
def __init__(self):
*optional ccode*
EXCERCISE 1. Implement a class „student‟ with default constructor that prints a message „An empty student object is
created‟
Write the program here:
Object Oriented Programming Lab Session 02 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
6
2. Modify the program in Exercise-1 and pass the arguments (Name, batch and year) using the same
__init__ method
3. If a program (class) contains two __init__ definitions such that
a. One __init__ defines only default parameter
b. The other __init__ defines the user defined parameter
Then which __init__ method will be executed. Specify the conditions
Write the program here:
Object Oriented Programming Lab Session 02 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
7
4. Develop a class that uses default constructor to modify a value of variable and prints it.
Write the program here:
Object Oriented Programming Lab Session 03 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
8
Lab Session 03
OBJECT Explore Different Types of Methods within a Single Class.
TYPES OF METHODS In Python, there exist three types of functions / methods:
Regular / free functions
Static methods / static member functions
Non-static methods / non-static member functions
A static method is a method that knows nothing about the class or instance it was called on. It just gets
the arguments that were passed, no implicit first argument. With static methods, neither self (the object
instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions
except that you can call them from an instance or the class:
Behind the scenes Python simply enforces the access restrictions by not passing in the self or
the cls argument when a static method gets called using the dot syntax. This confirms that static methods
can neither access the object instance state nor the class state. They work like regular functions but belong
to the class‟s (and every instance‟s) namespace.
A class method, the class of the object instance is implicitly passed as the first argument instead of self.If
you define something to be a class method, it is probably because user intends to call it from the class
rather than from a class instance.
GENERAL SYNTAX
class A(object):
def default_function(self):
**Statements**
@classmethod
def class_function(cls):
**Statements**
@staticmethod
def static_function():
**Statements**
Object Oriented Programming Lab Session 03 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
9
EXCERCISE
1. Develop a student class that has the following functions:
To take input name , roll_number, email_address from user
To take the count of courses and name of each course from user
To calculate GPA of the individual courses
To calculate CGPA of particular semester
Write the program here:
Object Oriented Programming Lab Session 03 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
10
2. Develop the class given in Q1 and demonstrates the working of three basic types of function present
in python.
Write the program here:
Object Oriented Programming Lab Session 04 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
11
Lab Session 04 OBJECT
Construct Classes using Inheritance.
INHERITANCE Inheritance is one of the cornerstones of OOP because it allows the creation of hierarchical classifications.
Using inheritance, you can create a general class that defines traits common to a set of related items. This
class may then be inherited by other, more specific classes, each adding only those things that are unique
to the inheriting class. In keeping with standard Python terminology, a class that is inherited is referred to
as a super class. The class that does the inheriting is called the derived class. Further, a derived class can
be used as a Super class for another derived class.
Things to remember:
Super classes are listed in parentheses in a class header
Classes inherit attributes from their super classes
Instances inherit attributes from all accessible classes.
GENERAL SYNTAX
class Parent(object):
*attributes*
*functions*
class Child(Parent):
*unique attributes*
*unique functions*
*parent attribute*
*parent functions*
class Child2(Parent):
*unique attributes*
*unique functions*
*parent attribute*
*parent functions*
Object Oriented Programming Lab Session 04 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
12
EXCERCISE
1. Develop a super class „person‟ , use default constructor to pass name as an argument and print its
name using a function. Define two child classes („student‟ and „teacher‟). For student class, attributes
of name , department and year should be passed as argument to default constructor. For teacher class,
attributes of name and course should be passed as argument to default constructor. Use same print
method (of super class) to print details of student and teacher class objects.
Attach printout here:
Object Oriented Programming Lab Session 04 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
13
2. Develop a parent class „Bank_Account‟ , use default constructor to pass account_number as an
argument and print it using a function. Define two child classes („Saving_Account‟ and
„Current_Account‟). For Saving_Account class, attributes of minimum_balance and interest_rate
should be passed as argument to default constructor. For Current_Account, attributes of
withdrawl_limit should be passed as argument to default constructor. Use same print method (of
super class) to print details of both child class objects.
Attach printout here:
Object Oriented Programming Lab Session 04 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
14
3. Develop a parent class „Employee‟ , use default constructor to pass Employee_id, Employee_name
and designation as arguments and print them using a function. Define three child classes („Manager‟,
„Team_lead‟ and „Clerk‟). For each of child class, specify unique attributes accordingly. Use same
print method (of super class) to print details of all three child class objects.
Attach printout here:
Object Oriented Programming Lab Session 05 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
15
Lab Session 05
OBJECT
Construct Classes using multiple Inheritance
MULTIPLE INHERITANCE Multiple inheritance is a property of some object-oriented computer programming languages in which
an object or class can inherit characteristics and features from more than one parent object or parent
class.
Super is used to return a proxy object that passes method calls to a parent or sibling class of type. This is
useful for accessing inherited methods that have been overridden in a class. The search order is same
except that the type itself is skipped.”
Use Case 1: Super can be called upon in a single inheritance, in order to refer to the parent class or
multiple classes without explicitly naming them.
Use Case 2: Super can be called upon in a dynamic execution environment for multiple or collaborative
inheritance
Sample Program
class Base(object):
def __init__(self):
print("Base")
class ChildA(Base):
def __init__(self):
print("ChildA ")
Base.__init__(self)
class ChildB(Base):
def __init__(self):
print("ChildB ")
super(ChildB, self).__init__()
>>> parent=Base()
Base
>>>a=ChildA()
ChildA
Base
>>>b=ChildB()
ChildB
Base
Object Oriented Programming Lab Session 05 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
16
EXCERCISE
1. Develop a class rectangle that takes width and height as argument in default constructor and
calculates area in the same default constructor.
2. Modify the class „square‟ that uses the rectangle class (defined in Exercise-1) as super class and calls
the default constructor using super key word to calculate area of square.
Write the program here:
Write the program here:
Object Oriented Programming Lab Session 05 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
17
3. Develop a class „Person‟ that has attributes of name and age. There are two methods in the same class
to print each of the attribute (name and age). Develop another class „Student‟ that has attributes of
student_id and roll_number. Implement a class resident for a person who is also the student.
Write the program here:
Object Oriented Programming Lab Session 05 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
18
4. Develop a class „Hospital‟ that has attributes of name and address. Develop two child classes of
„Doctor‟ (name, address and specialization ) and „Patient‟ (name, address and disease ).. Implement a
class „medical_test‟. Display the name of doctor, name of patient and medical test information when a
medical test is done.
Write the program here:
Object Oriented Programming Lab Session 06 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
19
Lab Session 06 OBJECT
Develop Class Diagrams.
Class Diagrams The browser provides a textual view of the classes in a system. Class diagrams are created to graphically
view the classes and packages in the system. Rose automatically creates a class diagram called Main in
the Logical View. This diagram may be opened by double-clicking on it in the browser. The Main class
diagram typically contains packages thus, by the end of development it is a graphical view of the major
architectural elements of the system. A package may be added to a class diagram by selecting it in the
browser and dragging it onto the class diagram.
Figure 6.1: The Class Diagram
Each package typically has its own main diagram which is a picture of its key packages and classes. To
create the Main class diagram for a package, double-click on the package on a class diagram. Once the
Main diagram is created for a package, you can add packages and classes to the diagram by selecting
them in the browser and dragging them onto the diagram.
Classes from any package may be added to a class diagram by selecting the class on the browser and
dragging it onto the open class diagram. If the Show Visibility option is set to true either as a default
Object Oriented Programming Lab Session 06 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
20
using the Tool:Options menu or individually by using the shortcut menu for the class, the name of the
“owning” package is displayed. The package name will be visible for all classes that do not belong to the
package owning the class diagram.
Packages and classes may also be created using the class diagram toolbar. To create a package or class
using the toolbar:
1. Click to select the icon (package or class) on the class diagram toolbar.
2. Click on the class diagram to place the package or class.
3. While the new package or class is still selected, enter its name.
4. Multiple packages or classes may be created by depressing and holding the Shift key.
Packages and classes created on class diagrams are automatically added to the browser.
To create a class diagram:
1. Right-click to select the owning package and make the shortcut menu visible.
2. Select the New:Class Diagram menu command. This will add a class diagram called
NewDiagram to the browser.
3. While the new class diagram is still selected, enter its name.
4. To open the class diagram, double-click on it in the browser.
Class Structure
The structure of a class is represented by its set of attributes. Attributes may be created in the browser, via
the Class Specification or on a class diagram.
To create an attribute in the browser:
1. Right-click to select the class in the browser and make the shortcut menu visible.
2. To create an attribute, select the New:Attribute menu command. This will add an attribute called
name to the browser.
3. While the new attribute is still selected, enter its name.
4. Attribute data types and default values may not be entered via the browser
To create an attribute using the Class Specification:
1. Right-click to select the class in the browser and make the shortcut menu visible.
2. Select the Specification menu command.
3. Select the Attributes tab.
4. Right-click to make the shortcut menu visible.
5. Select the Insert menu command. This will insert an attribute called name.
6. While the new attribute is still selected, enter its name. Type and initial value may be filled in at
this time or you may choose to fill in this information later in the development cycle.
To create an attribute on a class diagram:
1. Right-click to select the class on the class diagram and make the shortcut menu visible.
2. Select the Insert New Attribute menu command. This will insert an attribute in the form
name : type = initval
3. While the attribute is still selected, fill in its name. Type and initial value may be filled in at this
time or you may choose to fill in this information later in the development cycle.
Attributes of a class may be viewed in the browser. The class will be initially collapsed. To expand the
class to view its attributes, click the + next to the class.
Object Oriented Programming Lab Session 06 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
21
Attributes should be documented. To add the documentation for an attribute:
1. Click to select the attribute in the browser.
2. Position the cursor in the Documentation Window. If the Documentation Window is not visible,
select the View:Documentation menu command.
3. Enter the documentation for the attribute.
To delete an attribute:
1. Right-click to select the attribute in the browser or on the Attributes tab of the Class Specification
and make the shortcut menu visible.
2. Select the Delete menu command.
Class Behavior
The behavior of a class is represented by its set of operations. Operations may be created in the browser,
via the Class Specification or on a class diagram. To create an operation in the browser:
1. Right-click to select the class in the browser and make the shortcut menu visible.
2. To create an operation, select the New:Operation menu command. This will add an operation
called opname to the browser.
3. While the new operation is still selected, enter its name.
4. The operation signature may not be entered via the browser
To create an operation using the Class Specification:
1. Right-click to select the class in the browser and make the shortcut menu visible.
2. Select the Specification menu command.
3. Select the Operations tab.
4. Right-click to make the shortcut menu visible.
5. Select the Insert menu command. This will insert an attribute called opname.
6. While the new operation is still selected, enter its name. The signature and return value may be
filled in at this time or you may choose to fill in this information later in the development cycle.
To create an operation on a class diagram:
1. Right-click to select the class on the class diagram and make the shortcut menu visible.
2. Select the Insert New Operation menu command. This will insert an attribute in the form
opname ( argname : argtype = default) : return
3. While the operation is still selected, fill in its name. The signature and return value may be filled
in at this time or you may choose to fill in this information later in the development cycle.
Operations of a class may be viewed in the browser. The class will be initially collapsed. To expand the
class to view its operations, click the + next to the class.
To enter the signature of an operation:
1. Right-click to select the operation in the browser and make the shortcut menu visible.
2. Select the Specification menu command.
3. Select the Detail tab.
4. Right-click in the Arguments field to make the shortcut menu visible.
5. Select the Insert menu command. This will insert an argument called argname of type argtype
with a default value of default.
6. Click to select the name, type, or default and enter the desired information.
7. Click the OK button to close the Specification.
Object Oriented Programming Lab Session 06 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
22
To delete an operation:
1. Right-click to select the operation in the browser or on the Operations tab of the Class
Specification and make the shortcut menu visible.
2. Select the Delete menu command.
Operations should be documented.
To add the documentation for an operation: 1. Click to select the operation in the browser.
2. Position the cursor in the Documentation Window. If the Documentation Window is not visible,
select the View:Documentation menu command.
3. Enter the documentation for the operation.
Relationships
Relationships provide a conduit for communication. There are four different types of relationships :
association, aggregation, dependency, and inheritance. Relationships may only be created on a class
diagram using the toolbar.
Object Oriented Programming Lab Session 06 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
23
EXERCISES
1. Develop a Class Diagram using the specifications given below:
A class „Person‟ that has attributes of name and age. There are two methods in the same
class to print each of the attribute (name and age). Develop another class „Student‟ that
has attributes of student_id and roll_number. Implement a class resident for a person who
is also the student
Write the program here:
Object Oriented Programming Lab Session 06 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
24
A class „Hospital‟ that has attributes of name and address. Develop two child classes of „Doctor‟
(name, address and specialization ) and „Patient‟ (name, address and disease ).. Implement a
class „medical_test‟. Display the name of doctor, name of patient and medical test information
when a medical test is done
Write the program here:
Object Oriented Programming Lab Session 06 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
25
A parent class „Employee‟ , use default constructor to pass Employee_id, Employee_name and
designation as arguments and print them using a function. Define three child classes („Manager‟,
„Team_lead‟ and „Clerk‟). For each of child class, specify unique attributes accordingly. Use
same print method (of super class) to print details of all three child class objects
Write the program here:
Object Oriented Programming Lab Session 07 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
26
Lab Session 07
OBJECT
Resolve the Conflicts of Method Accessibility with Method Resolution Order (MRO).
METHOD RESOLUTION ORDER In Python, a class can inherit features and attributes from multiple classes which is the case of Multiple
Inheritance. The implementation of multiple inheritance complicates the way of searching with respect to
the order of parent class. First, the method or attribute is searched within a class and then it follows the
order we specified while inheriting. This order is also called Linearization of a class and set of rules are
called MRO(Method Resolution Order). MRO or Method Resolution Order defines the sequence in
which base classes are searched when looking for a method in the parent class.
Sample Program:
class A:
def method(self):
print ("I am in A")
class B(A):
def method(self):
print ("I am in B")
class C(A):
def method(self):
print ("I am in C")
class D(B, C):
pass
>>>d = D()
>>>d.method()
I am in B
Object Oriented Programming Lab Session 07 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
27
EXCERCISE
1. Apply MRO and write the output of following code
class A(object):
def innn(self):
print("in a")
class B(object):
def innn(self):
print("in b")
class X(A, B):
def innn(self):
print("in x")
class Y(B, A):
def innn(self):
print("in y")
class Z(X, Y):
def innn(self):
print("in z")
obj=z()
obj.innn()
2. Modify the code given in Exercise-1 to remove the error
Write the program here and attach the
printout of output
Write the program and output here:
Object Oriented Programming Lab Session 07 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
28
3. Write the search sequence of MRO after its application on code in Exercise-2. State the error and its
remedy in your own words
Write the MRO Sequence and Error here:
Object Oriented Programming Lab Session 08 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
29
Lab Session 08
OBJECT
Illustrate Use of Abstract Classes.
THEORY A class with an abstract method cannot be instantiated (that is, we cannot create an instance by calling it)
unless all of its abstract methods have been defined in subclasses
Sample Program
import abc
class AbstractClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def abstractMethod(self):
print('123')
return
class ConcreteClass(AbstractClass):
def __init__(self):
self.me = "me"
>>>c = ConcreteClass()
>>>c.abstractMethod()
TypeError: Can't instantiate abstract class ConcreteClass with abstract methods abstractMethod
Object Oriented Programming Lab Session 08 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
30
EXCERCISE
1. Write the output of the class given below.
from abc import ABCMeta, abstractmethod
class Super(metaclass=ABCMeta):
def delegate(self):
self.action()
@abstractmethod
def action(self):
pass
class Sub(Super): pass
>>>X = Sub()
2. Modify the program given in Exercise-1 to remove the error. Write program and its output below.
Write output here
Write the program here and the output
Object Oriented Programming Lab Session 08 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
31
3. Develop a class that covers two common properties / variables along with two distinguishing
properties of each of the vehicle (car, truck and motorcycle). Define separate class to cover the unique
properties of each of vehicle type. Use the concept of inheritance and abstraction to implement the
program. Define print function to print the output of each class.
Write the program here and the output
Object Oriented Programming Lab Session 08 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
32
4. Develop an abstract class that has two methods:
a. Input method to take two operands
b. Mathematical operation (abstract method)
Develop four child classes
a. Addition_operation
b. Subtraction_operation
c. Multiplication_operation
d. Deletion_operation
Implement the child classes in a way that the input taken in parent class can be used to perform
relevant mathematical operation in each of four child classes.
Write the program here and the output
Object Oriented Programming Lab Session 09 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
33
Lab Session 09
OBJECT Explore Built-in and User-Defined Meta Functions.
DECORATORS A function decorator is a sort of runtime declaration about the function that follows. A function decorator
is coded on a line by itself just before the def statement that defines a function or method. It consists of
the @ symbol, followed by what we call a meta-function—a function (or other callable object) that
manages another function. A decorator can return any sort of object; this allows the decorator to insert a
layer of logic to be run on every call.
SAMPLE PROGRAM:
def lets_decorate(func):
def inner_decoration():
##func()
print("I got decorated")
func()
return inner_decoration
@lets_decorate
def ordinary():
print("I am ordinary")
>>>ordinary()
I got decorated
I am ordinary
EXCERCISE
1. Write a program that divides two numbers and prints the output.
Write the program and output here
Object Oriented Programming Lab Session 09 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
34
2. Implement a decorator for Exercise-1 such that division must not be performed and error message
should be displayed if divisor is zero.
Write the program and the output here
Object Oriented Programming Lab Session 09 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
35
3. Develop two functions such that:
a) Print_x function that prints X in the given pattern
b) Print_y function that prints Y in the given pattern
User decorator approach to generate following pattern:
XXXXX
YYYYY
Hello
YYYYY
XXXXX
Write the program and the output here
Object Oriented Programming Lab Session 10 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
36
Lab Session 10
OBJECT
Illustrate Use of Polymorphism.
POLYMORPHISM In object-oriented programming, polymorphism (from the Greek meaning "having multiple
forms") is the characteristic of being able to assign a different meaning to a particular function or
"operator" in different contexts
EXCERCISE
1. Develop a super class „Animal‟ that takes name of animal as an argument to default constructor. The
super class should be implemented in such a way that it becomes mandatory for all child classes to
implement „talk‟ method if they want to instantiate the object. The child classes (cat and dog) should
return the relevant voices through „talk‟ method.
Write the program here and attach the printout of output
Object Oriented Programming Lab Session 10 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
37
2. Debug the program of Q-1 to show the assignment of operands to variables and selection of operator
through „debug control‟ window through single stepping, over and out options separately.
Write down the difference in execution observed in three debugging ways, also attach the
printout here:
Object Oriented Programming Lab Session 10 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
38
3. Develop a super class „Person‟. The super class has a method „ticket_price‟ which should be
implemented in such a way that it becomes mandatory for all child classes to implement „ticket_price‟
method if they want to instantiate the object. The child classes (Employed_person and student) should
return the relevant ticket prices after concession applicable to these categories.
Object Oriented Programming Lab Session 11 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
39
Lab Session 11
OBJECT
Practice Exception Handling.
EXCEPTION HANDLING An error result or an unpredictable behavior of your program not caused by the operating system but that
occurs in your program is called an exception. The ability to deal with a program‟s eventual abnormal
behavior is called exception handling. Using exception handling, your program can automatically invoke
an error-handling routine when an error occurs.
TYPES/METHODS:
Raise allows users to throw an exception at any time.
Assert enables users to verify if a certain condition is met and throw an exception if it isn‟t.
In the try clause, all statements are executed until an exception is encountered.
Except is used to catch and handle the exception(s) that are encountered in the try clause.
Else lets user code sections that should run only when no exceptions are encountered in the try
clause.
Finally enables you to execute sections of code that should always run, with or without any
previously encountered exceptions.
General Format:
try:
statements # Run this main action first
except name1:
statements # Run if name1 is raised during try block
except (name2, name3):
statements # Run if any of these exceptions occur
except name4 as var:
statements # Run if name4 is raised, assign instance raised to var
except:
statements # Run for all other exceptions raised
else:
statements # Run if no exception was raised during try block
Object Oriented Programming Lab Session 11 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
40
EXCERCISE 1. Develop a program that takes years of educations from users as input and gives following output.
a. If the years of education is less than or equal to 16 then its not enough
b. If user enters an invalid value then error message should be displayed
c. If user enters value greater than 16 then „you are eligible‟ should be displayed
Write the program here and attach the printout of output
Object Oriented Programming Lab Session 11 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
41
2. Develop a function „smart_division‟ with following exceptions:
a. If user enters invalid value then error should be displayed
b. If user enter 0 as divisor then user should be prompted for relevant error
c. If user enters correct values then output should be displayed
Write the program and output here
Object Oriented Programming Lab Session 11 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
42
3. Develop a function „factorial‟ with following exceptions:
a. If user enters invalid value then error should be displayed
b. If user enter 0 or negative valuethen user should be prompted for relevant error
c. If user enters positive numeric value then output should be displayed
4. Develop a user-defined exception / custom exception for any of single case discussed in Q1.
Write the program here and attach the printout of output
Write the program here and attach the printout of output
Object Oriented Programming Lab Session 12 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
43
Lab Session 12
OBJECT
Illustrate function overloading.
FUNCTION OVERLOADING In the context of programming, overloading refers to the ability of a function or an operator to behave in
different ways depending on the parameters that are passed to the function.
OVERLOADING BUILT-IN FUNCTIONS
Example -1:
class Shopping:
def __init__(self, basket, buyer_name):
self.basket = list(basket)
self.buyer_name = buyer_name
def __len__(self):
return len(self.basket);
purchase = Shopping(['Stationary', 'Food'], 'John')
print(len(purchase))
OVERLOADING USER-DEFINED FUNCTIONS
Example -1:
class Shopping:
def __init__(self, basket, buyer_name):
self.basket = list(basket)
self.buyer_name = buyer_name
def __len__(self):
return len(self.basket);
purchase = Shopping(['Stationary', 'Food'], 'John')
print(len(purchase))
Object Oriented Programming Lab Session 12 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
44
EXCERCISE
1. Implement built-in function “__str__” to print vector whose x and y coordinates will be provided by
user i.e. Vector (6, 9) will be printed as 6i+9j
2. Implement built-in function “__str__” to print point whose x and y coordinates will be provided by
user i.e. Point (2,3) will be printed as (2,3)
Write the program here:
Write the program here:
Object Oriented Programming Lab Session 12 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
45
3. Implement a user-defined function “Greetings” to print a message according to the condition defined
below:
a. If user specifies a name then he / she should be greeted as „Welcome user name‟
b. If user doesn‟t specify the name then he/she should be greeted with „Welcome‟
only
Write the program here:
Object Oriented Programming Lab Session 13 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
46
Lab Session 13 OBJECT
Illustrate Operator Overloading
OPERATOR OVERLOADING Operator overloading is done with the help of a special function, called operator function, which defines
the operations that the overloaded operator will perform relative to the class upon which it will work.
Operator overloading lets classes intercept normal Python operations. Classes can overload all Python
expression operators. Classes can also overload built-in operations such as printing, function calls,
attribute access, etc. Overloading makes class instances act more like built-in types.
Why do we need operator overloading?
Before we proceed further, you should know the reason that why we do operator overloading. Do we
really need it? For instance, compare the following syntaxes to perform addition of two objects a and b of
a user defined class fraction (assume class fraction has a member function called add() which adds two
fraction objects):
C = a.add(b);
C = a+b;
Which one is easier to use? Obviously the second one is easy to use and is more meaningful. After
overloading the appropriate operators, you can use objects in expressions in just the same way that you
use Python's built-in data types.
SAMPLE PROGRAM:
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
def getRadius(self):
return self.__radius
def __add__(self, another_circle):
return Circle( self.__radius + another_circle.__radius )
c1 = Circle(4)
print(c1.getRadius()) # output is 4
c2 = Circle(5)
print(c2.getRadius()) # output is 5
c3 = c1 + c2
print(c3.getRadius()) # output is 9
Object Oriented Programming Lab Session 13 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
47
EXCERCISE
1. Develop a point class and overload “add” operator such that two point in the form of x-coordinate and
y-coordinate can be added using „+‟ operator
2. Extend a point class in Q1 and overload “less than (__lt__) and greater than (__gt__)” operator such
that two point in the form of x-coordinate and y-coordinate can be compared using „<‟ and „>‟
operator.
Write your program here
Write your program here
Object Oriented Programming Lab Session 13 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
48
3. Develop a circle „class‟ and overload “less than (__lt__) and greater than (__gt__)” operator such that
two circles can be compared using „<‟ and „>‟ operator on the basis of radius provided input by user.
Write your program here
Object Oriented Programming Lab Session 13 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
49
4. Overload less than „lt‟ and greater than „gt‟ operator in such a way that if two points of the form
P1(X,Y) and P2(X,Y) are compared then the operator should return true or false based on the
magnitude of the two points compared.
Write your program here
Object Oriented Programming Lab Session 14 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
50
Lab Session 14
OBJECT
Explore structuring of projects using modules and packages
MODULES AND PACKAGES In this lab session, modules and import systems would be explored. Modules and packaging are the key
elements that enforce structure in projects.
For small programs, we can just put all our classes into one file and put some code at the end of the file to
start them interacting. However, as our projects grow, it can become difficult to find one class that needs
to be edited among the many classes we've defined. This is where modules come in. Modules are simply
Python files, nothing more. The single file in our small program is a module. Two Python files are two
modules. If we have two files in the same folder, we can load a class from one module for use in the other
module.
Assume we have a module called database.py that contains a class called Database, and a second module
called products.py that is responsible for product-related queries. At this point, we don't need to think too
much about the contents of these files. What we know is that products.py needs to instantiate the
Database class from database.py so it can execute queries on the product table in the database. There are
several variations on the import statement syntax that can be used to access the class.
Example
import database
db = database.Database()
# Do queries on db
This version imports the database module into the products namespace (the list of names currently
accessible in a module or function), so any class or function in the database module can be accessed using
database.<something> notation. Alternatively, we can import just the one class we need using the from...
import syntax:
Example
from database import Database
db = Database()
# Do queries on db
If for some reason, products already has a class called Database, and we don't want the two names to be
confused, we can rename the class when used inside the products module:
Example
from database import Database as DB
db = DB()
# Do queries on db
We can also import multiple items in one statement. If our database module also contains a Query class,
we can import both classes using:
from database import Database, Query
Organizing the modules
As a project grows into a collection of more and more modules, we may find that we want to add another
level of abstraction, some kind of nested hierarchy on our modules' levels. But we can't put modules
inside modules; one file can only hold one file, after all, and modules are nothing more than Python files.
Object Oriented Programming Lab Session 14 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
51
Files, however, can go in folders and so can modules. A package is a collection of modules in a folder.
The name of the package is the name of the folder. All we need to do to tell Python that a folder is a
package and place a (normally empty) file in the folder named __init__.py. If we forget this file, we won't
be able to import modules from that folder. Let's put our modules inside an ecommerce package in our
working folder, which will also contain a main.py to start the program. Let's additionally add another
package in the ecommerce package for various payment options. The folder hierarchy will look like this:
parent_directory/
main.py
ecommerce/
__init__.py
database.py
products.py
payments/
__init__.py
paypal.py
authorizenet.py
When importing modules or classes between packages, we have to be cautious about the syntax. In
Python 3, there are two ways of importing modules: absolute imports and relative imports.
Absolute imports Absolute imports specify the complete path to the module, function, or path we want
to import. If we need access to the Product class inside the products module, we could use any of these
syntaxes to do an absolute import:
import ecommerce.products
product = ecommerce.products.Product()
or
from ecommerce.products import Product
product = Product()
or
from ecommerce import products
product = products.Product()
The import statements separate packages or modules using the period as a separator.
Relative imports Relative imports are basically a way of saying "find a class, function, or module as it is positioned relative
to the current module".
Example
If we are working in the products module and we want to import the Database class from the database
module "next" to it, we could use a relative import:
from .database import Database
The period in front of database says, "Use the database module inside the current package". In this case,
the current package is the package containing the products.py file we are currently editing, that is, the
ecommerce package. If we were editing the paypal module inside the ecommerce.payments package, we
would want to say, "Use the database package inside the parent package", instead. That is easily done
with two periods:
from ..database import Database
We can use more periods to go further up the hierarchy.
Object Oriented Programming Lab Session 14 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
52
EXERCISE
1. Provide object-oriented code for a TO-DO application that can keep track of things you want to do each
day, and allow you to mark them as completed.
Write your program here
Object Oriented Programming Lab Session 14 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
53
2. Practice the package and module importing syntax. Add some functions in various modules and try
importing them from other modules and packages. Use relative and absolute imports.
Write your program here
Object Oriented Programming Lab Session 14 NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
54
3. For the class diagram below, do following:
a. Make a package with appropriate number of modules
b. Import the classes where necessary
c. Provide object-oriented code
Write your program here
Teacher’s Signature
DEPARTMENT OF COMPUTER & INFORMATION SYSTEMS ENGINEERING
BACHELORS IN COMPUTER SYSTEMS ENGINEERING
RUBRIC
Course Code: _______________ Week #: _______________ Lab #: _______________
Assigned task: __________________________________________________________________________________
______________________________________________________________________________________________
______________________________________________________________________________________________
CRITERIA AND SCALES
Criterion 1: To what level has the student understood the problem?
0 1 2
The student has no idea of the
problem.
The student has incomplete idea of
the problem.
The student has complete idea of the
problem.
Criterion 2: To what extent has the student implemented the solution?
0 1 2
The solution has not been
implemented. The solution is incomplete. The solution is complete.
Criterion 3: What level of creativity is evident in the proposed solution?
0 1 2
There is no solution. The solution is run of the mill. The solution is innovative.
Criterion 4: Answer to questions related to the task
0 1 2 3
The student did not answer
any question regarding lab
task.
The student answered a
few questions regarding lab
task.
The student answered most
of the questions regarding
lab task.
The student answered all
the questions regarding lab
task.
Criterion 5: To what extent is the student familiar with the scripting/programming interface?
0 1 2
The student is unfamiliar with the
interface.
The student is familiar with a few
features of the interface.
The student is proficient with the
interface.
Teacher’s Signature
DEPARTMENT OF COMPUTER & INFORMATION SYSTEMS ENGINEERING
BACHELORS IN COMPUTER SYSTEMS ENGINEERING
RUBRIC
Course Code: _______________ Week #: _______________ Lab #: _______________
Assigned task: __________________________________________________________________________________
______________________________________________________________________________________________
______________________________________________________________________________________________
CRITERIA AND SCALES
Criterion 1: To what level has the student understood the problem?
0 1 2
The student has no idea of the
problem.
The student has incomplete idea of
the problem.
The student has complete idea of the
problem.
Criterion 2: To what extent has the student implemented the solution?
0 1 2
The solution has not been
implemented. The solution is incomplete. The solution is complete.
Criterion 3: What level of creativity is evident in the proposed solution?
0 1 2
There is no solution. The solution is run of the mill. The solution is innovative.
Criterion 4: Answer to questions related to the task
0 1 2 3
The student did not answer
any question regarding lab
task.
The student answered a
few questions regarding lab
task.
The student answered most
of the questions regarding
lab task.
The student answered all
the questions regarding lab
task.
Criterion 5: To what extent is the student familiar with the scripting/programming interface?
0 1 2
The student is unfamiliar with the
interface.
The student is familiar with a few
features of the interface.
The student is proficient with the
interface.
Teacher’s Signature
DEPARTMENT OF COMPUTER & INFORMATION SYSTEMS ENGINEERING
BACHELORS IN COMPUTER SYSTEMS ENGINEERING
RUBRIC
Course Code: _______________ Week #: _______________ Lab #: _______________
Assigned task: __________________________________________________________________________________
______________________________________________________________________________________________
______________________________________________________________________________________________
CRITERIA AND SCALES
Criterion 1: To what level has the student understood the problem?
0 1 2
The student has no idea of the
problem.
The student has incomplete idea of
the problem.
The student has complete idea of the
problem.
Criterion 2: To what extent has the student implemented the solution?
0 1 2
The solution has not been
implemented. The solution is incomplete. The solution is complete.
Criterion 3: What level of creativity is evident in the proposed solution?
0 1 2
There is no solution. The solution is run of the mill. The solution is innovative.
Criterion 4: Answer to questions related to the task
0 1 2 3
The student did not answer
any question regarding lab
task.
The student answered a
few questions regarding lab
task.
The student answered most
of the questions regarding
lab task.
The student answered all
the questions regarding lab
task.
Criterion 5: To what extent is the student familiar with the scripting/programming interface?
0 1 2
The student is unfamiliar with the
interface.
The student is familiar with a few
features of the interface.
The student is proficient with the
interface.