Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Department of Basic Science and Humanities

Table of contents

Module 5: Introduction to Python Programming


No. Topics Page No
5.1 Classes and objects 5-1
5.2 Classes and functions 5-3
5.3 Classes and methods 5-4
Question Bank 5-7
Introduction to Python Programming [BPLCK105B/205B]

Module 5

5.1Classes and objects

1. What is class? How to define class in python? How to initiate a class and how
the class members are accessed?

* A class is programmer defined data type which binds data and functions
together into a single entity

* Class is defined using a keyword “Class”


ex: class Point :
pass
print (point)

* The process of creating a new object is called as instantiation and the object is
called as an instance of a class

P= point() => reference to the point object is created and assigned to p.

* Class members that is the attributes and methods can be accessed using the
object of a class

Syntax:
objectname.attributename

objectname.methodname()

2. Define class and object? What are programmer defined types? Explain with
examples?

* Class is user defined data type which binds data and function together into a
single entity. A class can have a set of variables also known as attributes and
member function also known as methods.

Class acts like a prototype/template/blueprint (no physical space or memory)

* Object: - an object is an instance of a class and it has physical existence. One


can create any number of objects for a class

Dr. Narasimha C. Dr. TTIT, KGF 5- 1


Introduction to Python Programming [BPLCK105B/205B]

*programmer defined types ie. a class in python can be created using a keyword
class. Here, we are creating an empty class without any members by just using
the keyword pass within it
class point :
pass
print(point)

output
<class __ main __ point>
The term __ main __ indicates that the class
point is in the main scope of the current module

P = point() reference is a point object is created and assigned to p

The process of the creating a new object is called as instantiation and the object
is instance of a class

point (p)
< __ main __ point object at 0x003C1BF0

3) Develop a program that uses class student which prompts the user to enter the
marks in three subjects, calculates total marks, percentage and displays the
details.

class Student:
def __init__(self, name = " ", usn = " ", marks = [0,0,0,0]):
self.name = name
self.usn = usn
self.marks = marks
def getMarks(self):
self.name = input(" Enter the student name :")
self.usn = input(" Enter the usn name :")
self.marks[0] = int(input(" Enter the marks in subject 1 :"))
self.marks[1] = int(input(" Enter the marks in subject 2 :"))
self.marks[2] = int(input(" Enter the marks in subject 3 :"))
self.marks[3] = self.marks[0] + self.marks[1] + self.marks[2]
def display(self):
print(self.name)
print(self.usn)
print(self.marks[0:3])
print("Total marks is :", self.marks[3])

Dr. Narasimha C. Dr. TTIT, KGF 5- 2


Introduction to Python Programming [BPLCK105B/205B]

print("Percentage :", self.marks[3]/3)


s1 = Student()
s1.getMarks()
s1.display()

Enter the usn name :Suresh


Enter the usn name :1GV23MI0028
[86, 75, 92]
Total marks is : 253
Percentage : 84.33333333333333

5.2 Classes and functions

4) Define pure functions. Illustrate with an example?


A pure function is a function which takes objects as arguments and does some
work without modifying any of the original arguments
Ex:
Class Time:
hours
minutes
seconds
def add_time(t1,t2):
Sum=Time()
Sum.hour=t1.hour+t2hour
Sum.minute=t1.minute+t2.minute
Sum.second=t1.second+t2.second
If Sum.second>=60:
Sum.second-=60
Sum.minute=1
If Sum.minute>=60:
Sum.minute-=60
Sum.hour t=1

Dr. Narasimha C. Dr. TTIT, KGF 5- 3


Introduction to Python Programming [BPLCK105B/205B]

Return sum
t1=time()
t1.hour=10
t1.minute=1
t1.second=14
t2=time()
t2.hour=2
t2.minute=4
t2.second=6
t3=time()
t3=add_time(t1,t2)
In the above example we have a class time and function add_time(t1,t2) it takes
two objects t1 and t2 adds the time (hour, min, sec) and prints without
modifying the original value of t1and t2.

5.3 Classes and methods

5) Explain __init__ special method with an example?


Ans: the __init__ method
The init (initialization) method is a special method that gets invoked when an
object is instantiated.
Ex:
# inside class Time:
def __init__(self, hour=0, minute=0, second=0):
Self.hour=hour
Self.minute=minute
Self.second=second
When we creat an object of class time:
>>time=Time() creating an object (instantiation)

Dr. Narasimha C. Dr. TTIT, KGF 5- 4


Introduction to Python Programming [BPLCK105B/205B]

Automatically the __init__ special method gets executed.


When no parameters are given during objects creation then the default values
are assigned
hour=0
minutes=0
seconds=0

>>when the object is created with values


time = Time(10,10,10)
then hours=10
minutes=10
seconds=10
It overrides the default values of 0

6) Explain __str__ method with an example?

__str__ is a special method like int that is supposed to return a string


representation of an object ex : string method for time objects.

# inside class Time:

def __str__(self):

return ‘%.2d:%.2d:%.2d’%(self.hour,self.minute,self.second)

When we print an object, python invokes the __str__ special method.

>> time = Time(9,45)

>> print(time)

o/p 09:45:00

Dr. Narasimha C. Dr. TTIT, KGF 5- 5


Introduction to Python Programming [BPLCK105B/205B]

7) Explain polymorphism with a suitable example?


Polymorphism means having many forms. Polymorphism means the same
function name but with different signatures, for multiples types.
Ex:
a)
def add(a,b,c=0):
return p+q+r
print(add(6,23))
print(add(10,20,30))

Here the function add is used to add the numbers. When the function is called
with the name and passing two arguments it will add two numbers and returns
the sum. The function is used to add three numbers also.

b) Addition operator
num1=1
num2=2
print(num1+num2)
o/p=3
str1=”python “
str2=”programming “
print(str1+” ” str2)
o/p=python programming

here we can see that single operators “ t” is used to carry addition operation on
integer data type and string data type (string concatenation)so the “+” operator
has different forms which is an occurrence of polymorphism in python

Dr. Narasimha C. Dr. TTIT, KGF 5- 6


Introduction to Python Programming [BPLCK105B/205B]

Question bank

1) What is class? How to define class in python? How to initiate a class and
how the class members are accessed explain with examples?
2) Explain __init__ and __str__ method with an example.

3) Explain operator overloading and polymorphism with example.

4) Define classes and objects in python. Create a class called Employee and
initialize with employee id and name. Design method to:

i) Set Age to assign age to the employee

ii) Set Salary to assign salary to the employee.

iii) Display to display all information of the employee.

5) Explain printing objects?

Dr. Narasimha C. Dr. TTIT, KGF 5- 7

You might also like