IPP M5 C2 Classes - Functions
IPP M5 C2 Classes - Functions
Chapter 15:
Classes and objects
Chapter 16:
Classes and functions
Chapter 17:
Classes and methods
Classes and Functions
Classes and Functions
• Functions are User Defined Functions
• Consider a Definition of Class
class Time :
pass
• New Objects of
Class the class
can be created
time = Time() time.hours =
11
time.minute = 59
time.search = 30
• User defined Function to
display
the attribute of object
say ob.
Two Kinds of Functions
1. Pure Functions
2. Modifiers
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)
EXERCISE
1. Write a function called mul_time that takes a Time object and a number and
returns a new Time object that contains the product of the original Time and
the number.
2. Write a program that takes a birthday as input and prints the user’s age and the
number of days, hours, minutes and seconds until their next birthday.
3. For two people born on different days, there is a day when one is twice as old as
the other. That’s their Double Day. Write a program that takes two birth dates
and computes their Double Day.
4. For a little more challenge, write the more general version that computes the
day when one person is n times older than the other.