12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

162 Chapter 17. Classes and methods>>> end = start.increment(1337, 460)TypeError: increment() takes exactly 2 arguments (3 given)The error message is initially confusing, because there are only two arguments in parentheses. Butthesubject isalsoconsidered an argument, soall together that’s three.17.4 Amorecomplicatedexampleis_after (from Exercise 16.2) is slightly more complicated because it takes two Time objects asparameters. Inthiscaseitisconventionaltonamethefirstparameterselfandthesecondparameterother:# inside class Time:def is_after(self, other):return self.time_to_int() > other.time_to_int()To usethis method, you have toinvoke it onone object and pass theother asan argument:>>> end.is_after(start)TrueOne nice thingabout thissyntax isthat italmost reads likeEnglish: “end isafter start?”17.5 Theinit methodThe init method (short for “initialization”) is a special method that gets invoked when an object isinstantiated. Its full name is__init__(two underscore characters, followed byinit, and then twomore underscores). Aninit method for theTimeclass might look likethis:# inside class Time:def __init__(self, hour=0, minute=0, second=0):self.hour = hourself.minute = minuteself.second = secondItiscommonfortheparametersof__init__tohavethesamenamesastheattributes. Thestatementself.hour = hourstoresthe value of the parameterhouras anattributeofself.The parameters areoptional, soifyou callTimewithno arguments, you get thedefault values.>>> time = Time()>>> time.print_time()00:00:00Ifyou provide one argument, itoverrideshour:

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

Saved successfully!

Ooh no, something went wrong!