15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

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.

mon - tue<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

TypeError: unsupported operand type(s) for -: 'Time60'<br />

and 'Time60'<br />

In-Place Addition<br />

With augmented assignment (introduced back in <strong>Python</strong> 2.0), we may also wish to override the "inplace"<br />

operators, for example, __iadd__(). This is for supporting an operation like mon += tue and having<br />

the correct result placed in mon. The only trick with overriding an __i*__() method is that it has to return<br />

self. Let us add the following bits of code to our example, fixing our repr() issue above as well as<br />

supporting augmented assignment:<br />

__repr__ = __str__<br />

def __iadd__(self, other):<br />

self.hr += other.hr<br />

self.min += other.min<br />

return self<br />

Here is our resulting output:<br />

>>> mon = Time60(10, 30)<br />

>>> tue = Time60(11, 15)<br />

>>> mon<br />

10:30<br />

>>> id(mon)<br />

401872<br />

>>> mon += tue<br />

>>> id(mon)<br />

401872<br />

>>> mon<br />

21:45<br />

Note the use of the id() built-in function to confirm that before and after the in-place addition we are<br />

indeed modifying the same object and not creating a new one. This is a great start at a class that has a<br />

lot of potential. The complete class definition for Time60 is given in Example 13.3.<br />

Example 13.3. Intermediate Customization (time60.py)

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

Saved successfully!

Ooh no, something went wrong!