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.

Appendix B<br />

Creating a new data type<br />

Object-oriented programming languages allow programmers <strong>to</strong> create new data<br />

types that behave much like built-in data types. We will explore this capability<br />

by building a Fraction class that works very much like the built-in numeric types:<br />

integers, longs and floats.<br />

Fractions, also known as rational numbers, are values that can be expressed as a<br />

ratio of whole numbers, such as 5/6. The <strong>to</strong>p number is called the numera<strong>to</strong>r and<br />

the bot<strong>to</strong>m number is called the denomina<strong>to</strong>r.<br />

We start by defining a Fraction class <strong>with</strong> an initialization method that provides<br />

the numera<strong>to</strong>r and denomina<strong>to</strong>r as integers:

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

Saved successfully!

Ooh no, something went wrong!