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.

17.6. The str method 163>>> time = Time (9)>>> time.print_time()09:00:00Ifyou provide twoarguments, they overridehourandminute.>>> time = Time(9, 45)>>> time.print_time()09:45:00And ifyou provide three arguments, they override all threedefault values.Exercise 17.2 Write an init method for the Point class that takes x and y as optional parametersand assigns them tothe corresponding attributes.17.6 The str method__str__isaspecial method, like__init__,that issupposed toreturn astringrepresentation of anobject.For example, here isastrmethod forTime objects:# inside class Time:def __str__(self):return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)When youprintan object, <strong>Python</strong> invokes thestrmethod:>>> time = Time(9, 45)>>> print time09:45:00When I write a new class, I almost always start by writing __init__, which makes it easier toinstantiateobjects, and__str__,which isuseful fordebugging.Exercise 17.3 Writeastrmethod forthePointclass. Create aPoint object and print it.17.7 OperatoroverloadingBy defining other special methods, you can specify the behavior of operators on user-defined types.For example, if you define a method named __add__ for the Time class, you can use the + operatoron Timeobjects.Here iswhat the definition might look like:# inside class Time:def __add__(self, other):seconds = self.time_to_int() + other.time_to_int()return int_to_time(seconds)

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

Saved successfully!

Ooh no, something went wrong!