Codecademy and the online textbook present object-oriented programming techniques that are founded on the concept of objects, which package together data, in the form of attributes, and actions, in the form of methods. Since the Tetris project relies on these techniques, perhaps we should discuss them.
In our programming exercises, up until now, we have used various types of objects, including integers, floats, strings, lists, and dictionaries. In Python, we can define classes to create new types of objects. The following Codecademy units present an introduction to classes.
Classes are also introduced in Chapters 12 to 16 of How to Think Like a Computer Scientist. Here, we can discuss the content of the Codecademy exercises, the online book, and other aspects of object oriented programming.
Following is a slightly modified version of code from a Codecademy exercise on classes that creates a
Point3D class to represent points in 3D space …
# a point in 3D space
def __init__(self, x, y, z):
# initialize a new Point3D object
self.x = x
self.y = y
self.z = z
# define a string representation of a Point3D object
return "(%d, %d, %d)" % (self.x, self.y, self.z)
# create two Point3D objects
my_point = Point3D(1, 2, 3)
your_point = Point3D(9, 8, 7)
# print the string representation of the two Point3D objects
(1, 2, 3)
(9, 8, 7)
Having defined a
Point3D class, as above, we could conveniently create
Point3D objects, and print string representations of their coordinates for output.