4.1 Classes and Objects 4.3 Classes and Methods
4.1 Classes and Objects 4.3 Classes and Methods
4.1 Classes and Objects 4.3 Classes and Methods
class ClassName:
“””Optional class documentation string' class_suite”””
class_suite
1. Pure Functions
2. Modifiers
4.1.1.1. Pure Function
• Prototype Development
• Planned Development
Prototype Development
• Prototype involves
– Writing a Rough draft of programs ( or prototype)
– Performing a basic calculation
– Testing on a few cases , correcting flaws as
we found them.
• Prototype development leads
code complicated
Planned Development
def convertToSeconds(t):
minutes = t.hours*60 + t.minutes
seconds = minutes *60 +
t.seconds return seconds
Example 2
def makeTime(seconds ):
time = Time()
time.hours = seconds//3600
time.minute = (seconds%3600)//60
time.seconds = seconds%60
return time
Example
def addTime(t1,t2):
seconds = convertToseconds(t1) + convertToseconds(t2)
return makeTime(seconds)
Module4
class Time:
"""Represents the time of day."""
def printTime(time):
print str(time.hours) + “:” str(time.minutes) “:” + str(time.seconds)
class Time:
def print_time(time):
print str(time.hours) + “:” str(time.minutes) “:” + str(time.seconds)
Example2
Class Time :
# previous method definition
here def increment(self,seconds):
self.seconds = seconds+ self.seconds
while self.seconds>=60:
self.seconds = self.seconds -60
self.minutes = self.minutes +1
while self.minute>=60:
self.minutes >=60 :
self.hours = self.hours +1
Invoking increment as a
method
>>> currentTime.increment(500)
4.2.4 Optional Arguments
currentTime = Time(9,14,30)
currenTime.print_time() -> 9:14:30
currentTime = Time()
currenTime.print_time() -> 0:0:0
currentTime = Time(9)
currenTime.print_time() -> 9:0:0
Invoking a method
currentTime = Time(9,14)
currenTime.print_time() -> 9:14:0
class Point :
def __init__(self,x=0,y=0):
self.x = x
self.y = y
def __str__(self):
return ‘(‘+str(self.x)+’,’+str(self.y)+’)
Method Overriding
P1 = Point (3,4)
P2 = Point(5,7)
P3 = P1 + P2
Print(P3) (8,11)
4.2.8 Polymorphism
def multadd(x, y, z)
return x*y + z
Invoking multadd()
• multadd(3,2,1) -> 7
• P1 = Point(3,4)
• P2 = Point(5,7)
• print multadd(2,P1,P2) -> (11,15)
• Print multadd(P1,P2,1) -> 44
A function like this that can take arguments
with different types is called polymorphic.
End of Module 4
https://proftgs.blogspot.in/