Objects

This tutorial is for Processing version 1.1+. If you see any errors or have comments, please let us know. This tutorial is from the book, Learning Processing, by Daniel Shiffman, published by Morgan Kaufmann Publishers, Copyright © 2008 Elsevier Inc. All rights reserved.

 

I'm Down with OOP

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: 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.

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.

Let's map out the data and functions for a very simple human object:

Human data Human functions 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 class. A classis different from an object. 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 instancesof the idea of a human being.

Think of a cookie cutter. A cookie cutter makes cookies, but it is not a cookie itself. The cookie cutter is the class, the cookies are the objects.

Using an Object

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., setup()and draw()) makes the world a better place.

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").

Data (Global Variables): Setup: Draw: 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:
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)

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 - color, location, speed. The object will also know about the stuff it can do, the methods (functions inside an object) - the car can driveand it can be displayed.

Using object-oriented design, the pseudocode improves to look something like this:

Data (Global Variables): Setup: Draw: 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).

Moving beyond pseudocode, the actual body of the sketch might look like:
myCar = Car()

def draw():
  background(255)
  myCar.drive()
  myCar.display()

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.

Writing the Cookie Cutter

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.

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.)

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.

# Simple non-OOP car
class Car(object):
The class name
c = color(255)
xpos = 100
ypos = 100
xspeed = 1
def __init__(self):
  self.c = color(255)
  self.xpos = 100
  self.ypos = 100
  self.xspeed = 1
Initializing data
def setup():
  size(200, 200)

def draw():
  background(0)
  display()
  drive()

def display():
  rectMode(CENTER)
  fill(c)
  rect(xpos, ypos, 20, 10)

def drive():
  xpos = xpos + xspeed
  if xpos > width:
  xpos = 0
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
Functionality


Class Name: The name is specified by class WhateverNameYouChoose(object). 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).

Data initialization: Python will automatically call a method named __init__ 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 self 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 __init__ method is analogous to "constructors" in other object-oriented languages, like Java and C++.)

Functionality: We can add functionality to our object by writing methods. The first parameter of every method (including __init__) should be self. 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.

Note that the code for a class exists as its own block and can be placed anywhere outside of setup() and draw(), as long as it's defined before you use it.

Using an Object: The Details

Earlier, we took a quick peek at how an object can greatly simplify the main parts of a Processing sketch (i.e. setup() and draw()).
# Step 1. Instantiate the object.
myCar = Car()

def setup():
  size(200, 200)

def draw():
  background(255)
  # Step 2. Call methods on the object. 
  myCar.drive()   
  myCar.display()
Let's look at the details behind the above steps outlining how to use an object in your sketch.

Step 1. Instantiating an object variable.

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:
# Variable Initialization   
var = 10   # var equals 10     

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 instantiate the object. We do this by calling the name of the class as though it were a function.
# Object instantiation
myCar = Car()

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 __init__ method, a special method that initializes all of the object's variables and makes sure the Car object is ready to go.

Step 2. Using an object

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)

In the case of the car, none of the available functions has an argument so it looks like:
# Functions are called with the "dot syntax". 
myCar.drive()
myCar.display()

Arguments to the __init__ method

In the above examples, the car object was initialized like so:
myCar = Car()

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?
# Creating two car objects    
myCar1 = Car()
myCar2 = Car()

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:

Make a new car.

We want to instead say:

Make a new red car, at location (0,10) with a speed of 1.

So that we could also say:

Make a new blue car, at location (0,100) with a speed of 2.

We can do this by placing arguments inside of the parentheses:
myCar = Car(color(255,0,0), 0, 100, 2)

The __init__ method must be rewritten to incorporate these arguments:
def __init__(self, c, xpos, ypos, xspeed):
  self.c = c   
  self.xpos = xpos
  self.ypos = ypos
  self.xspeed = xspeed

In my experience, the use of __init__ 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 __init__ method?"

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.



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 one purpose only, 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 x location, and so on. The __init__ methods arguments are just temporary, 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.

We can now take a look at the same sketch with multiple object instances, each with unique properties.
# 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()

Objects are data types too!

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.

If you were programming the Space Invaders game, for example, you might create a Spaceship class, an Enemy class, and a Bullet class, using an object for each entity in your game.

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 Fork and Spoon class. Moving on to a PlaceSetting class, you would likely include variables for both a Fork object and a Spoon object inside that class itself. This is perfectly reasonable and quite common in object-oriented programming.
class PlaceSetting(object):
  def __init__(self):
    fork = Fork()
    spoon = Spoon()

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.
def hit(self, bullet):
  bulletX = bullet.getX()
  bulletY = bullet.getY()
  # Code to determine if   
  # the bullet struck the enemy   

 

This tutorial is for Processing version 1.1+. If you see any errors or have comments, please let us know. This tutorial is from the book, Learning Processing, by Daniel Shiffman, published by Morgan Kaufmann Publishers, Copyright © 2008 Elsevier Inc. All rights reserved.