12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 16Classes and functions16.1 TimeAs another example of a user-defined type, we’ll define a class called Time that records the time ofday. The class definition looks likethis:class Time(object):"""represents the time of day.attributes: hour, minute, second"""We can create anewTimeobject and assignattributesfor hours, minutes, and seconds:time = Time()time.hour = 11time.minute = 59time.second = 30The statediagram fortheTimeobject looks like this:timeTimehourminutesecond115930Exercise16.1 Writeafunctioncalledprint_timethattakesaTimeobjectandprintsitintheformhour:minute:second. Hint: theformatsequence'%.2d'printsanintegerusingatleasttwodigits,including aleading zeroifnecessary.Exercise 16.2 Write a boolean function called is_after that takes two Time objects, t1 and t2,andreturnsTrueift1followst2chronologicallyandFalseotherwise. Challenge: don’tuseanifstatement.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!