06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

232 Creating a new data type<br />

class Fraction:<br />

def __init__(self, numera<strong>to</strong>r, denomina<strong>to</strong>r=1):<br />

self.numera<strong>to</strong>r = numera<strong>to</strong>r<br />

self.denomina<strong>to</strong>r = denomina<strong>to</strong>r<br />

The denomina<strong>to</strong>r is optional. A Fraction <strong>with</strong> just one parameter represents a<br />

whole number. If the numera<strong>to</strong>r is n, we build the Fraction n/1.<br />

Thenextstepis<strong>to</strong>writea str method that displays fractions in a way that<br />

makes sense. The form “numera<strong>to</strong>r/denomina<strong>to</strong>r” is natural here:<br />

class Fraction:<br />

...<br />

def __str__(self):<br />

return "%d/%d" % (self.numera<strong>to</strong>r, self.denomina<strong>to</strong>r)<br />

To test what we have so far, we put it in a file named Fraction.py and import<br />

it in<strong>to</strong> the <strong>Python</strong> interpreter. Then we create a fraction object and print it.<br />

>>> from Fraction import Fraction<br />

>>> spam = Fraction(5,6)<br />

>>> print "The fraction is", spam<br />

The fraction is 5/6<br />

As usual, the print command invokes the str method implicitly.<br />

B.1 Fraction multiplication<br />

We would like <strong>to</strong> be able <strong>to</strong> apply the normal addition, subtraction, multiplication,<br />

and division operations <strong>to</strong> fractions. To do this, we can overload the mathematical<br />

opera<strong>to</strong>rs for Fraction objects.<br />

We’ll start <strong>with</strong> multiplication because it is the easiest <strong>to</strong> implement. To multiply<br />

fractions, we create a new fraction <strong>with</strong> a numera<strong>to</strong>r that is the product<br />

of the original numera<strong>to</strong>rs and a denomina<strong>to</strong>r that is a product of the original<br />

denomina<strong>to</strong>rs. mul is the name <strong>Python</strong> uses for a method that overloads the<br />

* opera<strong>to</strong>r:<br />

class Fraction:<br />

...<br />

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

return Fraction(self.numera<strong>to</strong>r*other.numera<strong>to</strong>r,<br />

self.denomina<strong>to</strong>r*other.denomina<strong>to</strong>r)<br />

We can test this method by computing the product of two fractions:

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

Saved successfully!

Ooh no, something went wrong!