KEMBAR78
BPLCK205B Module 5 Notes | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
48 views38 pages

BPLCK205B Module 5 Notes

Module 5 of the Introduction to Python Programming course covers classes and objects, functions, and methods in Python. It explains the concepts of object-oriented programming, including class definitions, attributes, methods, and the use of the __init__() function. The module also provides examples of creating and manipulating objects, as well as concepts like inheritance, operator overloading, and polymorphism.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views38 pages

BPLCK205B Module 5 Notes

Module 5 of the Introduction to Python Programming course covers classes and objects, functions, and methods in Python. It explains the concepts of object-oriented programming, including class definitions, attributes, methods, and the use of the __init__() function. The module also provides examples of creating and manipulating objects, as well as concepts like inheritance, operator overloading, and polymorphism.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

Module 5

Classes and Objects, Classes and Functions,


Classes and Methods

Classes and objects: Programmer-defined types, Attributes, Rectangles, Instances as


return values, Objects are mutable, Copying,
Classes and functions: Time, Pure functions, Modifiers, Prototyping versus planning,
Classes and methods: Object-oriented features, Printing objects, Another example, A
more complicated example, The init method, The __str__ method, Operator overloading,
Type-based dispatch, Polymorphism, Interface and implementation.

Textbook 2: Chapters 15 – 17
RBT: L1, L2, L3

Textbook 1: Al Sweigart, “Automate the Boring Stuff with Python”, 1st Edition, No Starch Press,
2015. (Available under CC-BY-NC-SA license at https://automatetheboringstuff.com/)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 1 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

5.1. Classes and Objects

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 2 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

• Python is an object oriented programming language. Almost everything in Python is an object,


with its properties and methods.
• A Class is like an object constructor, or a "blueprint" for creating objects.
• Some points on Python class:
o Classes are created by keyword class.
o Attributes are the variables that belong to class.
o Attributes are always public and can be accessed using dot (.) operator.
• Eg.: Myclass.Myattribute

Overview of Object Oriented Terminology


• Class and Class variable
• Object
• Method
• Instance variable → A variable that is defined inside a method
• Function overloading
• Operator overloading
• Inheritance

5.2. Programmer-defined types (class)


• Python’s has built-in types; to define a new type as an example, we will create a type called
Point that represents a point in two-dimensional space

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 3 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

• In mathematical notation, points are often written in parentheses with a comma separating the
coordinates.
• For example, (0, 0) represents the origin, and (x, y) represents the point x units to the right and y
units up from the origin.

• A programmer-defined type is also called a class. A class definition looks like this:
class Point: """Represents a point in 2-D space."""

>>> obj=Point()
>>> obj #<__main__.Point object at 0x0000018B1D134EB0>

• To create a class, use the keyword class:


• Example: Create a class named MyClass, with a property named x:
class ClassName:
'Optional class documentation string'
class_suite

• The class has a documentation string, which can be accessed via ClassName.__doc__. The class_suite
consists of all the component statements defining class members, data attributes and functions.
• Syntax
class MyClass:
# member variables
variable1 = something
variable2 = something
# member functions / Methods
def function1(self, parameter1, ...):
self.variable1 = something else
# defining a new variable
self.variable3 = something
function1 statements...
def function2(self, parameter1, ...):
self.variable2 = something else
function2 statements...
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 4 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

• Example
class MyClass:
x=5
p1 = MyClass() #p1 is an object of MyClass
print(p1.x) #5→print value of x using dot op

The __init__() Function


• __init__() function is built-in function
• All classes have a function called __init__(), which is always executed when the class is being
initiated.
• Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
• The word 'self' is used to represent the instance of a class. By using the "self" keyword we access
the attributes and methods of the class in python.

Note: The __init__() function is called automatically every time the class is being used to create a
new object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Raju", 36)
print(p1.name) #Raju
print(p1.age) #36

• Objects can also contain methods. Methods in objects are functions that belong to the object.
• Example: Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 5 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

p1 = Person("Raju", 36)
p1.myfunc()

Self parameter
• The self parameter is a reference to the current instance of the class, and is used to access variables that
belongs to the class. It does not have to be named self, you can call it whatever you like, but it has to
be the first parameter of any function in the class:
• Example: Use the words myobj and abc instead of self:
class Person:
def __init__(myobj, name, age):
myobj.name = name
myobj.age = age
def myfunc(abc): #can use myobj, also instead of abc
print("Hello my name is " + abc.name) #displays name

p1 = Person("Raju", 36)
p1.myfunc()

• Modify Object Properties


class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name) #prints name

p1 = Person("Raju", 36)
p1.age = 40
p1.myfunc()
print(p1.age) Modify Object Properties

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 6 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

Delete Object Properties


class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name) #prints name

p1 = Person("Raju", 36)
del p1.age
print(p1.age)

The pass Statement


• Class definitions cannot be empty, but if you for some reason have a class definition with no
content, put in the pass statement to avoid getting an error.
• Example
class Person:
pass
# having an empty class definition like this, would raise an error without the pass statement

Creating an object of a class


• Class is mere a blueprint or a template. No storage is assigned when we define a class. Objects
are instances of class, which holds the data variables declared in the class and the member
functions work on these class objects.
• Example: To create an object of Point, you call Point as if it were a function.
class Point:
"""Represents a point in 2-D space."""
blank = Point()
print(blank) #<__main__.Point object at 0xb7e9d3ac>

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 7 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

5.3. Attributes
• We can assign values to an instance using dot notation:
>>> class Point:
pass
>>> blank = Point()
>>> blank.x = 3.0
>>> blank.y = 4.0
>>>blank1=Point()
>>>blank1.a=10
>>>blank1.b=20

• The variable blank refers to a Point object, which contains two attributes. Each attribute refers to
a floating-point number.
>>> blank.y #4.0
>>> x = blank.x
>>> x #3.0

• There is no conflict between the variable x and the attribute x. Use dot notation as part of any
expression. For example:
>>> '(%g, %g)' % (blank.x, blank.y) #'(3.0, 4.0)'
>>> import math
>>> distance = math.sqrt(blank.x**2 + blank.y**2)
>>> distance

5.4. Rectangles
• To design a class to represent rectangles.
• The attributes of an object can be of two possibilities: You could specify one corner of the rectangle
(or the center), the width, and the height. You could specify two opposing corners.
• Here is the class definition:
class Rectangle:
"""Represents a rectangle.
attributes: width, height, corner."""

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 8 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

• To represent a rectangle, you have to instantiate a Rectangle object and assign values to the
attributes:
>>> box = Rectangle()
>>> box #<__main__.Rectangle object at 0x03D1C50>
>>>box.width = 100.0 #box.width #100.0
>>>box.height = 200.0 #box.height #200.0
>>>box.corner = Point() #<__main__.Point object at 0x03D1BEB0>
>>>box.corner.x = 0.0
>>>box.corner.y = 0.0

• The expression box.corner.x means, “Go to the object box and select the attribute named corner;
then go to that object and select the attribute named x.”
box → corner → x

• Example of class Employee: To display employee details and count number of employees
class Employee:
#Common base class for all employees
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)

#Create first object of Employee class


emp1 = Employee("Raju", 2000)
#Create second object of Employee class
emp2 = Employee("Manu", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee Count: %d" % Employee.empCount)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 9 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

5.5. Instances as return values


• Functions can return values and also instances
# Python program to demonstrate returning value
def add(a, b):
# returning sum of a and b
return a + b
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
print("Result of add function is %d“ %res)

• For example, find_center takes a Rectangle as an argument and returns a Point that contains the
coordinates of the center of the Rectangle:
class Point:
"""Represents a point in 2-D space."""
class Rectangle:
"""Represents a rectangle attributes: width, height, corner."""
def find_center(rect):
#Returns a Point at the center of a Rectangle, returns: new Point
p = Point()
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2
return p

box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
center=find_center(box)
print(center.x,center.y) #50, 100

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 10 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

5.6. Objects are mutable


• We can change the state of an object by making an assignment to one of its attributes. For example,
to change the size of a rectangle without changing its position, you can modify the values of width
and height:
box.width = box.width + 50
box.height = box.height + 100
• We can also write functions that modify objects. For example, grow_rectangle takes a Rectangle
object and two numbers, dwidth and dheight, and adds the numbers to the width and height of the
rectangle:
def grow_rectangle(rect, dwidth, dheight):
rect.width += dwidth
rect.height += dheight
Here is an example that demonstrates the effect:
>>> box.width, box.height #(150.0, 300.0)
>>> grow_rectangle(box, 50, 100)
>>> box.width, box.height #(200.0, 400.0)

Objects are mutable: Program to add function


class Rectangle:
"""Represents a rectangle attributes: width, height, corner."""

def grow_rectangle(rect, dwidth, dheight):


rect.width += dwidth
rect.height += dheight

box = Rectangle()
box.width = 100.0
box.height = 200.0
#changing the values of objects
box.width = box.width + 50
box.height = box.height + 100

#display new values of box object


print(box.width,box.height) #150.0 300.0

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 11 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

grow_rectangle(box, 50, 100)


print(box.width,box.height) #200.0 400.0

5.7. Copying
• Copying an object is often an alternative to aliasing. The copy module contains a function called
copy that can duplicate any object:
>>> import copy
>>> class Point:
pass
>>> p1 = Point()
>>> p1.x = 3.0
>>> p1.y = 4.0
>>> p2 = copy.copy(p1) #p1 and p2 contain the same data, but they are not the same Point.
>>> p1 is p2 #False
>>> p1 == p2 #False

• The default behavior of the == operator is the same as the is operator; it checks object identity,
not object equivalence. If you use copy.copy to duplicate a Rectangle, you will find that it copies
the Rectangle object but not the embedded Point.
>>> box2 = copy.copy(box)
>>> box2 is box #False
>>> box2.corner is box.corner #True
• Operation is shallow copy because it copies the object and any references it contains, but not
the embedded objects.

Shallow Copying
• copy.copy copies the object but not the embedded object this operation is known as shallow
copy.
import copy
class Point:
pass
class Box:
pass
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 12 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

b = Box()
b.width = 100.0
b.height = 200.0
b.corner = Point()
b.corner.x = 0.0
b.corner.y = 0.0
b1 = copy.copy(b)
print(b is b1)
print(b.corner is b1.corner)

Deep Copying
• The copy module provides a method named deepcopy that copies not only the object but also the
objects it refers to, and the objects they refer to, and so on.
>>> box3 = copy.deepcopy(box)
>>> box3 is box #False
>>> box3.corner is box.corner #False

• box3 and box are completely separate objects.


import copy
class Point:
pass
class Box:
pass

b = Box()
b.width = 100.0
b.height = 200.0
b.corner = Point()
b.corner.x = 0.0
b.corner.y = 0.0
b1 = copy.deepcopy(b)
print(b is b1)
print(b.corner is b1.corner)
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 13 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

Program to demonstrate the copy and deepcopy


import copy
class Point:
"""Represents a point in 2-D space."""
def print_point(p):
"""Print a Point object in human-readable format."""
print("(%g, %g)" % (p.x, p.y))
class Rectangle:
"""Represents a rectangle attributes: width, height, corner."""

p1=Point()
p1.x=3.0
p1.y=4.0
print("p1 Contents: ")
print_point(p1)
p2=copy.copy(p1)
print("p2 Contents: ")
print_point(p2)
print("p1 is p2: "), p1 is p2)
print("p1 == p2: ", p1==p2)
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
box3 = copy.deepcopy(box)
print("box Contents: ",box.width,box.height,box.corner.x,box.corner.y)
print("box3Contents: ",box3.width,box3.height,box3.corner.x,box3.corner.y)
print("box3 is box: ",box3 is box )
print("box3.corner is box.corner:", box3.corner is box.corner)

Output:
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 14 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

p1 Contents: (3, 4) p2 Contents: (3, 4)


p1 is p2: False p1 == p2: False
box Contents: 100.0 200.0 0.0 0.0
box3 Contents: 100.0 200.0 0.0 0.0
box3 is box: False box3.corner is box.corner: False

Debugging
• If we try to access an attribute that does not exist we get an AttributeError
class Point:
pass
p = Point()
p.x =10
p.y= 20
print(p.x)
print(p.y)
print(p.z) # AttributeError
isinstance function can be used to check if an object is instance of a class
>>> isinstance(p,Point) # returns True
hasattr function is used to check if object has a particular attribute or not
>>> hasattr(p,’x’) # returns True
>>> hasattr(p,’z’) # returns False

Debugging with try statement


try:
data = p.x
except AttributeError:
data = 0

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 15 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

5.8. Classes and Functions: Time


• As another example of a programmer-defined type, define a class called Time that records the
time of day.
• The class definition
class Time:
"""Represents the time of day.
attributes: hour, minute, second"""
• Create a new Time object and assign attributes
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
#define function print_time
def print_time(t):
"""Print a Time object in human-readable format."""
print("(%.2d:%.2d:%.2d)" % (t.hour, t.minute, t.second))

• Time: Program to print time in hour:minute:second format


class Time:
"""Represents the time of day. attributes: hour, minute, second"""
def print_time(t):
"""Print a Time object in human-readable format."""
print("(%.2d:%.2d:%2d)" % (t.hour, t.minute, t.second))
time = Time() #define object of Time
time.hour = 11 #assign values to object
time.minute = 59
time.second = 30
print_time(time) #display time (11:59:30)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 16 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

5.9. Pure Functions


• Pure function is a function which does not modify any of the objects passed to it as an
arguments and it has no effect, like displaying a value or getting user input, other than returning
a value.
• Here is a simple prototype of add_time:
class Time:
pass
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
return sum
• The function creates a new Time object, initializes its attributes, and returns a reference to the
new object. This is called a pure function because it does not modify any of the objects passed to
it as arguments and it has no effect.
>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 0
>>> duration = Time()
>>> duration.hour = 1
>>> duration.minute = 35
>>> duration.second = 0
>>> done = add_time(start, duration)
>>> print_time(done) #10:80:00
• Here’s an improved version which take cares when where the number of seconds or minutes
adds up to more than sixty.
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 17 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

if sum.second >= 60:


sum.second -= 60
sum.minute += 1
if sum.minute >= 60:
sum.minute -= 60
sum.hour += 1
return sum

Pure Functions: Program to add to time objects


class Time:
"""Represents the time of day, attributes: hour, minute, second"""
def print_time(t):
"""Print a Time object in human-readable format."""
print("(%.2d:%.2d:%2d)" % (t.hour, t.minute, t.second))
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
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 += 1
return sum
start = Time()
start.hour = 9
start.minute = 48
start.second = 9
duration = Time()
duration.hour = 1
duration.minute = 35
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 18 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

duration.second = 2
done = add_time(start, duration)
print_time(done) # (11:23:11)

5.10. Modifiers
• Sometimes it is useful for a function to modify the objects it gets as parameters. In that case, the
changes are visible to the caller.
• Functions that work this way are called modifiers. increment, which adds a given number of
seconds to a Time object, can be written naturally as a modifier.

def increment(time, seconds):


time.second += seconds
if time.second >= 60:
time.second -= 60
time.minute += 1
if time.minute >= 60:
time.minute -= 60
time.hour += 1

5.11. Prototyping versus planning


• To convert Time objects to integers and take advantage of the fact that the computer knows how
to do integer arithmetic. Here is a function that converts Times object to integers:
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
• And here is a function that converts an integer to a Time by using divmod (divides the first
argument by the second and returns the quotient and remainder as a tuple).
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 19 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

• To test them is to check that time_to_int(int_to_time(x)) == x for many values of x. This is an


example of a consistency check.
def add_time(t1, t2):
seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)
Program to convert given time to seconds (integer form)
class Time:
"""Represents the time of day.
attributes: hour, minute, second"""
def print_time(t):
"""Print a Time object in human-readable format."""
print("(%.2d:%.2d:%2d)" % (t.hour, t.minute, t.second))
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
t = Time()
t.hour = 9
t.minute = 48
t.second = 40
print_time(t) # (09:48:40)
sec = time_to_int(t)
print("Time in Seconds: ",sec) # Time in Seconds: 35320

Program to convert seconds (integer form) to Time


class Time:
"""Represents the time of day.
attributes: hour, minute, second"""

def print_time(t):
"""Print a Time object in human-readable format."""
print("(%.2d:%.2d:%2d)" % (t.hour, t.minute, t.second))

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 20 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
t = Time()
sec = 35320
t = int_to_time(sec)
print_time(t) # (09:48:40)

Modified program to add two time objects using time to integer and integer to time functions
class Time:
"""Represents the time of day, attributes: hour, minute, second""“
def print_time(t):
"""Print a Time object in human-readable format."""
print("(%.2d:%.2d:%2d)" % (t.hour, t.minute, t.second))
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def add_time(t1, t2):
seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)
t1 = Time()
t1.hour = 9
t1.minute = 48
t1.second = 9
t2 = Time()
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 21 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

t2.hour = 10
t2.minute = 50
t2.second = 23
t3=add_time(t1,t2)
print_time(t3) #(20:38:32)

5.12. Classes and Methods


• Python is an object-oriented programming language, which means that it provides features that
support object-oriented programming, which has these defining characteristics:
o Programs include class and method definitions.
o Most of the computation is expressed in terms of operations on objects.
o Objects often represent things in the real world, and methods often correspond to the
ways things in the real world interact.
• Methods are semantically the same as functions, but there are two syntactic differences:
o Methods are defined inside a class definition in order to make the relationship between
the class and the method explicit.

• The syntax for invoking a method is different from the syntax for calling a function.
o Method is called by its name, but it is associated to an object (dependent).
o A method is implicitly passed the object on which it is invoked.
o It may or may not return any data.
o A method can operate on the data (instance variables) that is contained by the corresponding
class

• Basic Method Structure in Python:


Method Function
class class_name: class class_name:
def method_name () : pass
...... def function_name () :
# method body ......
... # function body
......

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 22 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

Python Methods: User-Defined Method:


class ABC :
def method_abc (self):
print("I am in method_abc of ABC class. ")

class_ref = ABC() # object of ABC class


class_ref.method_abc()
Functions
• Function is block of code that is also called by its name. (independent)
• The function can have different parameters or may not have any at all. If any data (parameters)
are passed, they are passed explicitly.
• It may or may not return any data.
• Function does not deal with Class and its instance concept.
• Basic Function Structure in Python:
def function_name ( arg1, arg2, ...) :
......
# function body
......

• Python 3 User-Defined Function:


def Subtract (a, b):
return (a-b)
print( Subtract(10, 12) ) # prints -2
print( Subtract(15, 6) ) # prints 9

Difference between method and function


• Simply, function and method both look similar as they perform in almost similar way, but the key
difference is the concept of ‘Class and its Object‘.
• Functions can be called only by its name, as it is defined independently. But methods can’t be
called by its name only, we need to invoke the class by a reference of that class in which it is
defined, i.e. method is defined within a class and hence they are dependent on that class
• To make print_time as a method, all we have to do is move the function definition inside the class
definition. Notice the change in indentation.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 23 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

class Time:
def print_time(time):
print('%.2d:%.2d:%.2d' % (time.hour, time.minute,
time.second))

• Define Function to print time


class Time:
"""Represents the time of day."""
def print_time(time):
print(“%.2d:%.2d:%.2d” % (time.hour, time.minute, time.second))

• To call this function, pass a Time object as an argument:


>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 00
>>> print_time(start) #09:45:00

• To define Method to print time (First Way)


class Time:
"""Represents the time of day."""
def print_time(time): #Method
print(“%.2d:%.2d:%.2d” % (time.hour, time.minute, time.second))

• To call this function, pass a Time object as an argument:


>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 00
>>> Time.print_time(start) #09:45:00

• To define Method to print time (Second Way)


class Time:
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 24 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

"""Represents the time of day."""


def print_time(time): #Method
print(“%.2d:%.2d:%.2d” % (time.hour, time.minute, time.second))

• To call this function, pass a Time object as an argument:


>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 00
>>> start.print_time() #09:45:00

Defining the Function and Method in a program


class Time:
"""Represents the time of day."""

#Method of Time
def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)

#Method of Time
def time_to_int(self):
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds

def print_time(self):
print("%.2d:%.2d:%.2d" % (self.hour, self.minute, self.second))

#Function (as we have not called int_to_time thorugh object)


def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 25 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

return time

start = Time()
start.hour = 9
start.minute = 45
start.second = 00
start.print_time() #09:45:00
end = start.increment(1337)
end.print_time() #10:07:17

• This mechanism can be confusing, especially if you make an error.


• For example, if you invoke increment with two arguments, you get:
>>> end = start.increment(1337, 460)
# inside class Time:
def is_after(self, other):
return self.time_to_int() > other.time_to_int()
To use this method, you have to invoke it on one object and pass the other as an argument:
>>> end.is_after(start) #True

5.13. A more complicated example


• Rewriting is_after slightly more complicated because it takes two Time objects as parameters. In
this case it is conventional to name the first parameter self and the second parameter other:
class Time:
"""Represents the time of day."""
#Method of Time
def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)
def time_to_int(self):
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 26 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

def print_time(self):
print("%.2d:%.2d:%.2d" % (self.hour, self.minute, self.second))

#Method of Time
def is_after(self, other):
return self.time_to_int() > other.time_to_int()
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time

start = Time()
start.hour = 9
start.minute = 45
start.second = 00
start.print_time() #09:45:00
end = start.increment(1337)
end.print_time() #10:07:17
print(end.is_after(start)) #True

5.14. The __init__ method


• The init method (short for “initialization”) is a special method that gets invoked when an object is
instantiated. Its full name is __init__ (two underscore characters, followed by init, and then two
more underscores). An init method for the Time class might look like this:
class Time:
# inside class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
• The parameters are optional, so if you call Time with no arguments, you get the default values.
>>> time = Time()
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 27 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

>>> time.print_time() #00:00:00


• If you provide one argument, it overrides hour:
>>> time = Time (9)
>>> time.print_time() #09:00:00
• If you provide two arguments, they override hour and minute.
>>> time = Time(9, 45)
>>> time.print_time() #09:45:00
• And if you provide three arguments, they override all three default values.
>>> time = Time(9, 45,24)
>>> time.print_time() #09:45:24

Program to use __init__ method by taking variable arguments (no arg, one arg, two arg ..)
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def print_time(self):
print("%.2d:%.2d:%.2d" % (self.hour, self.minute, self.second))

time = Time() #No arguments


time.print_time() #00:00:00
time = Time(9) #One argument
time.print_time() #09:00:00
time = Time(9,45) #Two arg
time.print_time() #09:45:00
time = Time(9,45,24) #Three arg
time.print_time() #09:4:24

5.15. The __str__ method


• __str__ is a special method, like __init__, that is supposed to return a string representation of an
object.
• For example, here is a str method for Time objects:
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 28 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

Class Time:
# inside class Time:
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
When you print an object, Python invokes the str method:
>>> time = Time(9, 45)
>>> print(time) #09:45:00

Program to demonstrate __str__ method


class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return "%.2d:%.2d:%.2d" % (self.hour, self.minute, self.second)

time = Time(9,45,23) #called __init__()


print(time) #python invokes __str__ method automatically (09:45:23)

5.16. Operator Overloading


• By defining other special methods, you can specify the behaviour of operators on programmer-
defined types. For example, if you define a method named __add__ for the Time class, you can
use the + operator on Time objects.
# inside class Time:
def __add__(self, other):
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)

And here is how you could use it:


>>> start = Time(9, 45)
>>> duration = Time(1, 35)
>>> print(start + duration) #11:20:00
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 29 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

When + operator is applied to Time objects, Python invokes __add__.

Program to demonstrate operator overloading


• Python Program illustrate how to overload a binary + operator
class A:
def __init__(self, a):
self.a = a
# adding two objects
def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Python ")
ob4 = A("Programming")
print(ob1 + ob2) #3 print(ob3 + ob4) #Python Programming

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 30 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

• Program to demonstrate operator overloading to add 2 complex numbers


class complex:
def __init__(self, a, b):
self.a = a
self.b = b
# adding two objects
def __add__(self, other):
return self.a + other.a, self.b + other.b
def __str__(self):
return self.a, self.b

Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3) #(3, 5)

• Program to demonstrate operator overloading for time


class Time:
# inside class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second

# inside class Time:


def __str__(self):
return "%.2d:%.2d:%.2d" % (self.hour, self.minute, self.second)

# inside class Time:


def time_to_int(self):
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 31 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

# inside class Time:


def __add__(self, other):
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)

#Function (to convert seconds to time)


def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time

start = Time(9,45,30)
duration = Time(1,35,40)
print(start + duration) #11:21:10

5.17. Type-based dispatch


• The built-in function isinstance( ) takes a value (other) and a class object, and returns True if the
value is an instance of the class.
• If other is a Time object, __add__ invokes add_time. Otherwise it assumes that the parameter
is a number and invokes increment. This operation is called a type-based dispatch because it
dispatches the computation to different methods based on the type of the arguments.
• The following is a version of __add__ that checks the type of other and invokes either add_time
or increment:
# inside class Time:
def __add__(self, other):
if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)
• The following is a version of __add__ that checks the type of other and invokes either add_time
or increment:

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 32 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

def add_time(self, other):


seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)
• The following is a version of __add__ that checks the type of other and invokes either def
increment(self, seconds):

seconds += self.time_to_int()
return int_to_time(seconds)
• Here are examples that use the + operator with different types:
>>> start = Time(9, 45)
>>> duration = Time(1, 35)
>>> print(start + duration) #11:20:00
>>> print(start + 1337) #10:07:17

• Program to demonstrate different operator types of operator overloading


class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second

def __add__(self, other):


if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)

# inside class Time:


def add_time(self, other):
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 33 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

# inside class Time:


def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)

# inside class Time:


def __str__(self):
return "%.2d:%.2d:%.2d" % (self.hour, self.minute, self.second)

# inside class Time:


def time_to_int(self):
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds

#Function (to convert seconds to time)


def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time

start = Time(9,45,30)
duration = Time(1,35,40)
print(start + duration) #11:21:10
print(start + 1337) #10:07:47

• Unfortunately, this implementation of addition is not commutative. If the integer is the first
operand, you get
>>> print(1337 + start)
TypeError: unsupported operand type(s) for +: 'int' and 'instance‘
• The problem is, instead of asking the Time object to add an integer, Python is asking an integer
to add a Time object, and it doesn’t know how.
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 34 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

• The special method __radd__, which stands for “right-side add”. This method is invoked when a
Time object appears on the right side of the + operator.
# inside class Time:
def __radd__(self, other):
return self.__add__(other)
And here’s how it’s used:
>>> print(1337 + start) #10:07:47

5.18. Polymorphism
• Type-based dispatch is useful when it is necessary, but (fortunately) it is not always necessary.
Often you can avoid it by writing functions that work correctly for arguments with different types.
• Example: histogram to count the number of times each letter appears in a word.
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c]+1
return d
• This function not only works on strings but also works for lists, tuples, and even dictionaries,
as long as the elements of s are hashable, so they can be used as keys in d.
>>> t = ['spam', 'egg', 'spam', 'spam', 'bacon', 'spam']
>>> histogram(t) #{'spam': 4, 'egg': 1, 'bacon': 1}

• Functions that work with several types are called polymorphic. Polymorphism can facilitate
code reuse.
• For example, the built-in function sum, which adds the elements of a sequence, works as long as
the elements of the sequence support addition.
• Since Time objects provide an add method, they work with sum:
>>> t1 = Time(7, 43)
>>> t2 = Time(7, 41)
>>> t3 = Time(7, 37)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 35 of 38


Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

>>> total = sum([t1, t2, t3])


>>> print(total) #23:01:00
• Example of inbuilt polymorphic functions:
# Python program to demonstrate in-built polymorphic functions
# len() being used for a string
print(len("Python Programming")) #18
# len() being used for a list
print(len([10, 20, 30])) #3
Example of used defined polymorphic functions:
def add(x, y=0, z = 0):
return x + y + z

print(add(2)) #2
print(add(2, 3)) #5
print(add(2, 3, 4)) #9

• But, if we does not initialize with default values, then python will raise error:
Print(add())

Polymorphism with a Function and objects:


class India: #we can use class India(): also
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")

class USA:
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 36 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

def type(self):
print("USA is a developed country.")

def func(obj):
obj.capital()
obj.language()
obj.type()
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)

Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Polymorphism with Inheritance:


class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 37 of 38
Introduction to Python Programming (BPLCK205B) Module 5: Classes and Objects, Functions, Methods

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.

5.19. Interface and implementation

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 38 of 38

You might also like