forked from jdf/processing-py-site
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
602 lines (522 loc) · 18.5 KB
/
index.html
File metadata and controls
602 lines (522 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta name="generator" content=
"HTML Tidy for Mac OS X (vers 31 October 2006 - Apple Inc. build 15.12), see www.w3.org">
<style type="text/css">
.obj_table { border-collapse: collapse; }
.obj_table td { vertical-align: top; padding: 5px; }
.obj_yellow { background-color: yellow; }
</style>
<title></title>
</head>
<body>
<h1>Objects</h1>
<p class="license">This tutorial is for Processing version 1.1+.
If you see any errors or have comments, please <a href=
"https://github.com/jdf/processing-py-site/issues?state=open">
let us know</a>. This tutorial is from the book, <a href=
"http://www.processing.org/learning/books/#shiffman">Learning
Processing</a>, by Daniel Shiffman, published by Morgan Kaufmann
Publishers, Copyright © 2008 Elsevier Inc. All rights
reserved.</p>
<p> </p>
<h3>I'm Down with OOP</h3>Before we begin examining the details
of how object-oriented programming (OOP) works in Processing,
let's embark on a short conceptual discussion of "objects"
themselves. Imagine you were not programming in Processing, but
were instead writing out a program for your day, a list of
instructions, if you will. It might start out something like:
<ul>
<li>Wake up.</li>
<li>Drink coffee (or tea).</li>
<li>Eat breakfast: cereal, blueberries, and soy milk.</li>
<li>Ride the subway.</li>
</ul>What is involved here? Specifically, what things are
involved? First, although it may not be immediately apparent from
how we wrote the above instructions, the main thing is you , a
human being, a person. You exhibit certain properties. You look a
certain way; perhaps you have brown hair, wear glasses, and
appear slightly nerdy. You also have the ability to do stuff ,
such as wake up (presumably you can also sleep), eat, or ride the
subway. An object is just like you, a thing that has properties
and can do stuff.<br>
<br>
So how does this relate to programming? The properties of an
object are variables; and the things an object can do are
functions. Object-oriented programming is the marriage of all of
the programming fundamentals: data and functionality.<br>
<br>
Let's map out the data and functions for a very simple human
object:<br>
<br>
<strong>Human data</strong>
<ul>
<li>Height.</li>
<li>Weight.</li>
<li>Gender.</li>
<li>Eye color.</li>
<li>Hair color.</li>
</ul><strong>Human functions</strong>
<ul>
<li>Sleep.</li>
<li>Wake up.</li>
<li>Eat.</li>
<li>Ride some form of transportation.</li>
</ul>Now, before we get too much further, we need to embark on a
brief metaphysical digression. The above structure is not a human
being itself; it simply describes the idea, or the concept,
behind a human being. It describes what it is to be human. To be
human is to have height, hair, to sleep, to eat, and so on. This
is a crucial distinction for programming objects. This human
being template is known as a <em>class</em>. A <em>class</em>is
different from an <em>object</em>. You are an object. I am an
object. That guy on the subway is an object. Albert Einstein is
an object. We are all people, real world <em>instances</em>of the
idea of a human being.<br>
<br>
Think of a cookie cutter. A cookie cutter makes cookies, but it
is not a cookie itself. The cookie cutter is the <em>class</em>,
the cookies are the <em>objects</em>.
<h3>Using an Object</h3>Before we look at the actual writing of a
class itself, let's briefly look at how using objects in our main
program (i.e., <strong>setup()</strong>and
<strong>draw()</strong>) makes the world a better place.<br>
<br>
Consider the pseudo-code for a simple sketch that moves a
rectangle horizontally across the window (we'll think of this
rectangle as a "car").<br>
<br>
<strong>Data (Global Variables)</strong>:
<ul>
<li>Car color.</li>
<li>Car x location.</li>
<li>Car y location.</li>
<li>Car x speed.</li>
</ul><strong>Setup</strong>:
<ul>
<li>Initialize car color.</li>
<li>Initialize car location to starting point.</li>
<li>Initialize car speed.</li>
</ul><strong>Draw</strong>:
<ul>
<li>Fill background.</li>
<li>Display car at location with color.</li>
<li>Increment car's location by speed.</li>
</ul>To implement the above pseudo-code, we would define global
variables at the top of the program, initialized them in setup(),
and call functions to move and display the car in draw().
Something like:
<pre>
c = color(0)
x = 0.0
y = 100.0
speed = 1.0
def setup():
size(200, 200)
def draw():
background(255)
move()
display()
def move():
global x
x = x + speed
if x > width:
x = 0
def display():
fill(c)
rect(x, y, 30, 10)
</pre><br>
Object-oriented programming allows us to take all of the
variables and functions out of the main program and store them
inside a car object. A car object will know about its data -
<em>color</em>, <em>location</em>, <em>speed</em>. The object
will also know about the <em>stuff it can do</em>, the methods
(functions inside an object) - the car can <em>drive</em>and it
can be <em>displayed</em>.<br>
<br>
Using object-oriented design, the pseudocode improves to look
something like this:<br>
<br>
<strong>Data (Global Variables)</strong>:
<ul>
<li>Car object.</li>
</ul><strong>Setup</strong>:
<ul>
<li>Initialize car object.</li>
</ul><strong>Draw</strong>:
<ul>
<li>Fill background.</li>
<li>Display car object.</li>
<li>Drive car object.</li>
</ul>Notice we removed all of the global variables from the first
example. Instead of having separate variables for car color, car
location, and car speed, we now have only one variable, a Car
variable! And instead of initializing those three variables, we
initialize one thing, the Car object. Where did those variables
go? They still exist, only now they live inside of the Car object
(and will be defined in the Car class, which we will get to in a
moment).<br>
<br>
Moving beyond pseudocode, the actual body of the sketch might
look like:
<pre>
myCar = Car()
def draw():
background(255)
myCar.drive()
myCar.display()
</pre><br>
We are going to get into the details regarding the above code in
a moment, but before we do so, let's take a look at how the Car
class itself is written.
<h3>Writing the Cookie Cutter</h3>The simple Car example above
demonstrates how the use of objects in Processing makes for
clean, readable code. The hard work goes into writing the object
template, that is the class itself. When you are first learning
about object-oriented programming, it is often a useful exercise
to take a program written without objects and, not changing the
functionality at all, rewrite it using objects. We will do
exactly this with the car example, recreating exactly the same
look and behavior in an object-oriented manner.<br>
<br>
All classes must include four elements: name, data
initialization, and methods. (Technically, the only actual
required element is the class name, but the point of doing
object-oriented programming is to include all of these.)<br>
<br>
Here is how we can take the elements from a simple
non-object-oriented sketch and place them into a Car class, from
which we will then be able to make Car objects.<br>
<br>
<table width="656">
<tr>
<td></td>
</tr>
<tr>
<td class="obj_pre">
<pre>
# Simple non-OOP car
</pre>
</td>
<td>→</td>
<td class="obj_post">
<pre>
class Car(object):
</pre>
</td>
<td>→</td>
<td class="obj_desc">The class name</td>
</tr>
<tr>
<td class="obj_pre obj_yellow">
<pre>
c = color(255)
xpos = 100
ypos = 100
xspeed = 1
</pre>
</td>
<td>→</td>
<td class="obj_post obj_yellow">
<pre>
def __init__(self):
self.c = color(255)
self.xpos = 100
self.ypos = 100
self.xspeed = 1
</pre>
</td>
<td>→</td>
<td class="obj_desc">Initializing data</td>
</tr>
<tr>
<td class="obj_pre">
<pre>
def setup():
size(200, 200)
def draw():
background(0)
display()
drive()
</pre>
</td>
<td></td>
<td class="obj_post"></td>
<td></td>
<td class="obj_desc"></td>
</tr>
<tr>
<td class="obj_pre obj_yellow">
<pre>
def display():
rectMode(CENTER)
fill(c)
rect(xpos, ypos, 20, 10)
def drive():
xpos = xpos + xspeed
if xpos > width:
xpos = 0
</pre>
</td>
<td>→</td>
<td class="obj_post obj_yellow">
<pre>
def display(self):
rectMode(CENTER)
fill(self.c)
rect(self.xpos, self.ypos,
20, 10)
def drive(self):
self.xpos += self.xspeed
if self.xpos > width:
self.xpos = 0
</pre>
</td>
<td>→</td>
<td class="obj_desc">Functionality</td>
</tr>
</table><br>
<br>
<strong>Class Name</strong>: The name is specified by <tt>class
WhateverNameYouChoose(object)</tt>. We then enclose all of the
code for the class in an indented block. Class names are
traditionally capitalized (to distinguish them from variable
names, which traditionally are lowercase).<br>
<br>
<strong>Data initialization</strong>: Python will automatically
call a method named <tt>__init__</tt> whenever you create an
object from a class. You should define this method in your class
and initialize its data here. When you're writing code inside of
a method, there's a special word <tt>self</tt> that allows you to
set variables that are defined on each individual instance of a
class. Variables defined this way are often referred to as
"instance variables." (The <tt>__init__</tt> method is analogous
to "constructors" in other object-oriented languages, like Java
and C++.)<br>
<br>
<strong>Functionality</strong>: We can add functionality to our
object by writing methods. The first parameter of every method
(including <tt>__init__</tt>) should be <tt>self</tt>. Python
automatically passes this parameter to the method when you call
it; it's what allows you to access each object's instance
variables inside of the method.<br>
<br>
Note that the code for a class exists as its own block and can be
placed anywhere outside of <strong>setup()</strong> and
<strong>draw()</strong>, as long as it's defined before you use
it.
<h3>Using an Object: The Details</h3>Earlier, we took a quick
peek at how an object can greatly simplify the main parts of a
Processing sketch (i.e. <strong>setup()</strong> and
<strong>draw()</strong>).
<pre>
<strong># Step 1. Instantiate the object.</strong>
myCar = Car()
def setup():
size(200, 200)
def draw():
background(255)
<strong># Step 2. Call methods on the object.</strong>
myCar.drive()
myCar.display()
</pre>Let's look at the details behind the above steps outlining
how to use an object in your sketch.<br>
<br>
<strong>Step 1. Instantiating an object variable.</strong><br>
<br>
In order to initialize a variable (i.e., give it a starting
value), we use an assignment operation - variable equals
something. With other Python data types, it looks like this:
<pre>
# Variable Initialization
var = 10 # var equals 10
</pre><br>
Initializing an object is a bit more complex. Instead of simply
assigning it a value, like with an integer or floating point
number, we have to <i>instantiate</i> the object. We do this by
calling the name of the class as though it were a function.
<pre>
# Object instantiation
myCar = Car()
</pre><br>
In the above example, "myCar" is the object variable name and "="
indicates we are setting it equal to something, that something
being a new instance of a Car object. What we are really doing
here is initializing a Car object. When you initialize a
primitive variable, such as an integer, you just set it equal to
a number. But an object may contain multiple pieces of data.
Recalling the Car class, we see that this line of code calls the
<em>__init__ method</em>, a special method that initializes all
of the object's variables and makes sure the Car object is ready
to go.<br>
<br>
<strong>Step 2. Using an object</strong><br>
<br>
Once we have successfully instantiated an object, we can use it.
Using an object involves calling methods that are built into that
object. A human object can eat, a car can drive, a dog can bark.
Calling a function inside of an object is accomplished via dot
syntax: variableName.objectFunction(Function Arguments)<br>
<br>
In the case of the car, none of the available functions has an
argument so it looks like:
<pre>
# Functions are called with the "dot syntax".
myCar.drive()
myCar.display()
</pre>
<h3>Arguments to the __init__ method</h3>In the above examples,
the car object was initialized like so:
<pre>
myCar = Car()
</pre><br>
This was a useful simplification while we learned the basics of
OOP. Nonetheless, there is a rather serious problem with the
above code. What if we wanted to write a program with two car
objects?
<pre>
# Creating two car objects
myCar1 = Car()
myCar2 = Car()
</pre><br>
This accomplishes our goal; the code will produce two car
objects, one stored in the variable myCar1 and one in myCar2.
However, if you study the Car class, you will notice that these
two cars will be identical: each one will be colored white, start
in the middle of the screen, and have a speed of 1. In English,
the above reads:<br>
<br>
<strong><em>Make a new car.</em></strong><br>
<br>
We want to instead say:<br>
<br>
<strong><em>Make a new red car, at location (0,10) with a speed
of 1.</em></strong><br>
<br>
So that we could also say:<br>
<br>
<strong><em>Make a new blue car, at location (0,100) with a speed
of 2.</em></strong><br>
<br>
We can do this by placing arguments inside of the parentheses:
<pre>
myCar = Car(color(255,0,0), 0, 100, 2)
</pre><br>
The <tt>__init__</tt> method must be rewritten to incorporate
these arguments:
<pre>
def __init__(self, c, xpos, ypos, xspeed):
self.c = c
self.xpos = xpos
self.ypos = ypos
self.xspeed = xspeed
</pre><br>
In my experience, the use of <tt>__init__</tt> method arguments
to initialize object variables can be somewhat bewildering.
Please do not blame yourself. The code is strange-looking and can
seem awfully redundant: "For every single variable I want, I have
to add an argument to the <tt>__init__</tt> method?"<br>
<br>
Nevertheless, this is quite an important skill to learn, and,
ultimately, is one of the things that makes object-oriented
programming powerful. But for now, it may feel painful. Let's
looks at how parameter works in this context.<br>
<br>
<img src="imgs/init_arguments.png"><br>
<br>
Parameters are local variables used inside the body of a function
that get filled with values when the function is called. In the
examples, they have <em>one purpose only</em>, which is to
initialize the variables inside of an object. These are the
variables that count, the car's actual color, the car's actual
<em>x</em> location, and so on. The <tt>__init__</tt> methods
arguments are just <em>temporary</em>, and exist solely to pass a
value from where the object is made into the object itself. You
can name these function parameters whatever you want, of
course—they don't have to have the same names as the
instance variables. However, it is advisable to choose a name
that makes sense to you, and also to stay consistent.<br>
<br>
We can now take a look at the same sketch with multiple object
instances, each with unique properties.
<pre>
# Even though there are multiple objects, we still only need one class.
# No matter how many cookies we make, only one cookie cutter is needed.
class Car(object):
# The Constructor is defined with arguments.
def __init__(self, c, xpos, ypos, xspeed):
self.c = c
self.xpos = xpos
self.ypos = ypos
self.xspeed = xspeed
def display(self):
stroke(0)
fill(self.c)
rectMode(CENTER)
rect(self.xpos, self.ypos, 20, 10);
def drive(self):
self.xpos = self.xpos + self.xspeed;
if self.xpos > width:
self.xpos = 0
myCar1 = Car(color(255, 0, 0), 0, 100, 2)
myCar2 = Car(color(0, 255, 255), 0, 10, 1)
def setup():
size(200,200)
def draw():
background(255)
myCar1.drive()
myCar1.display()
myCar2.drive()
myCar2.display()
</pre>
<h3>Objects are data types too!</h3>Assuming this is your first
experience with object-oriented programming, it's important to
take it easy. The examples here just one class and make, at most,
two or three objects from that class. Nevertheless, there are no
actual limitations. A Processing sketch can include as many
classes as you feel like writing.<br>
<br>
If you were programming the Space Invaders game, for example, you
might create a <em>Spaceship</em> class, an <em>Enemy</em> class,
and a <em>Bullet</em> class, using an object for each entity in
your game.<br>
<br>
In addition, although not primitive, classes are data types just
like integers and floats. And since classes are made up of data,
an object can therefore contain other objects! For example, let's
assume you had just finished programming a <em>Fork</em> and
<em>Spoon</em> class. Moving on to a <em>PlaceSetting</em> class,
you would likely include variables for both a <em>Fork</em>
object and a <em>Spoon</em> object inside that class itself. This
is perfectly reasonable and quite common in object-oriented
programming.
<pre>
class PlaceSetting(object):
def __init__(self):
fork = Fork()
spoon = Spoon()
</pre><br>
Objects, just like any data type, can also be passed in as
arguments to a function. In the Space Invaders game example, if
the spaceship shoots the bullet at the enemy, we would probably
want to write a function inside the Enemy class to determine if
the Enemy had been hit by the bullet.
<pre>
def hit(self, bullet):
bulletX = bullet.getX()
bulletY = bullet.getY()
# Code to determine if
# the bullet struck the enemy
</pre>
<p> </p>
<p class="license">This tutorial is for Processing version 1.1+.
If you see any errors or have comments, please <a href=
"https://github.com/jdf/processing-py-site/issues?state=open">
let us know</a>. This tutorial is from the book, <a href=
"http://www.processing.org/learning/books/#shiffman">Learning
Processing</a>, by Daniel Shiffman, published by Morgan Kaufmann
Publishers, Copyright © 2008 Elsevier Inc. All rights
reserved.</p>
</body>
</html>