OOP Lab 3
OOP Lab 3
Overview:
A constructor is a special kind of method that Python calls when it instantiates an object
using the definitions found in your class. Python relies on the constructor to perform tasks
such as initializing (assigning values to) any instance variables that the object will need when
it starts. Constructors can also verify that there are enough resources for the object and
perform any other start-up task you can think of.
The name of a constructor is always the same, __init__(). The constructor can accept
arguments when necessary to create the object. When you create a class without a
constructor, Python automatically creates a default constructor for you that doesn’t do
anything. Every class must have a constructor, even if it simply relies on the default
constructor.
The following steps demonstrate how to create a constructor: This type of function is also
called constructors in Object Oriented Programming (OOP). We normally use it to initialize
all the variables.
Example 1:
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('Aaaah ...')
self.hungry = False
else:
print('No, thanks!')
This example provides you a simple example of constructor. In this case, the
constructor __init__(self) accepts one parameter.
Example 2:
class Point:
def __init__( self):
print ("i m constructor")
pt1 = Point()
pt2 = Point()
pt3 = Point()
def Functio(self):
self.sum=self.x+self.y
return self .sum
pt1 = Point(3,4)
pt2 = Point(2,3)
pt3 = Point(5,7)
LAB TASKS
You are required to complete the following tasks in the Lab and submit
your solution on LMS in PDF file format.
Task 1: Create a class called date having day, month, and year as its data members
and getdate() and putdate() as its member functions. Instantiate the class, ask user
to enter date and display the date. Write constructor function in the class to initialize
the date object with 01/01/2000.
Task 2: Write Python programs which defines a class Vehicle with attributes as
Model and CC. Define two functions consumption and speed that should get Model
and CC values from the constructor and show the consumption and speed of car.
Create an object of Vehicle class. Display object values (Model & CC) on screen.