Chapter 16. Classes and Objects
At this point we have defined classes and created objects that represent the time of day and the day of the year. And we’ve defined methods that create, modify, and perform computations with these objects.
In this chapter we’ll continue our tour of object-oriented programming (OOP) by defining classes that represent geometric objects, including points, lines, rectangles, and circles. We’ll write methods that create and modify these objects, and we’ll use the jupyturtle module to draw them.
I’ll use these classes to demonstrate OOP topics including object identity and equivalence, shallow and deep copying, and polymorphism.
Creating a Point
In computer graphics, a location on the screen is often represented using a pair of coordinates in an x-y plane. By convention, the point (0, 0) usually represents the upper-left corner of the screen, and (x, y) represents the point x units to the right and y units down from the origin. Compared to the Cartesian coordinate system you might have seen in a math class, the y-axis is upside down.
There are several ways we might represent a point in Python:
-
We can store the coordinates separately in two variables,
xandy. -
We can store the coordinates as elements in a list or tuple.
-
We can create a new type to represent points as objects.
In object-oriented programming, it would be most idiomatic to create a new type. To do that, we’ll start with a class definition for Point:
classPoint:"""Represents a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access