GIS Logo GSP 118 (318): GIS Programming

An Introduction to Classes

In Review

1. Introduction

Classes are a part of "Object Oriented Programming". You've already used classes in Python including "Lists" and "Strings". Classes are a powerful part of designing software that is easy to to use and support as you can "encapsulate" functionality within the class as you already have with functions. With a class you can encapsulate related functions that operate on the same type of data. Now you'll learn to create your own classes.

A class is a grouping of functions and variables. You can then create "instances" of a class and call functions within the class to modify the variables within the class. You've already done this with strings. For instance, in the following code we create a string and then split the string based on slash's. The sequence of characters are a variable within the string and then the "split()" function is a function within the class.

TheString="11/1/2011"
TheDateElements=TheString.split("/")

Classes are a powerful way to expand programs for a large variety of applications. This includes spatial modeling. The idea is that you can create a "class" that defines how a particular type of objects behave. The objects can repesent people, animals, trees, buildings, or just about anything. The classes allow us to define the properties (also refered to as variables) for each type (or class) of object. The class for people might have variables like height, sex, weight, and income range. A class for trees might have species and height. These variables can be hidden inside the class so we don't have to constantly pass them into the functions that work on the objects. Even more importantly, we can create lists of many objects and manage them in the same way.

The example below shows how to create a very simple "Spatiall Explicit Individually Based Model" in Python. This is a model that contains objects that are spatially referenced where each object represents an individual. The individeuals in this case are "blobs" but could be any type of animal.

The example relies on the tkinter library to display the objects as they move from left to right. This also maes it an example of how to use modeless windows to display animated data in Python.

2. Blob Class

Below is a class that represents a "blob" within a tkinter window. The class contains a number of functions that are explained below. Copy the class into the Wing IDE and then review the contents of the class based on the descriptions below.

It is very easy to create your own classes in Python. Enter the code below:

#################################################################
# A blob that can be moved in a canvas
# Heavliy modified from: http://effbot.org/tkinterbook/canvas.htm
# Author: Jim Graham
# Date: 2/27/2013
#################################################################

class Blob:
	# Initialize the new object
	# Inputs:
	#  canvas - the canvas widget that the blob will appear in
	#  Position - a list of the x and y pixel coordinate for the starting location of the blob
	#  FillColor - the color of the Blob
	#  MovementAmount - The Amount to move the Blob for each time Move() is called
	def __init__(self, TheCanvas, Coordinate, FillColor, MovementAmount):

		self.TheCanvas = TheCanvas # save the canvas the blob is in

		# save the amount to move for later
		self.MovementAmount = MovementAmount

		# create the oval at an x and y location based on movement
		self.id = self.TheCanvas.create_oval(Coordinate[0], Coordinate[1],
		    Coordinate[0]+20, Coordinate[1]+20,fill=FillColor)

	# move the blob based on the MovementAmount
	def move(self):
		# get the existing coordinate of the blob
		Coordinate = self.TheCanvas.coords(self.id)

		# if the blob has moved off the frame, reverse the direction of movement
		if Coordinate[2] >= self.TheCanvas.winfo_width():
			self.MovementAmount = -self.MovementAmount
		if Coordinate[0] < 0:
			self.MovementAmount = -self.MovementAmount

		self.TheCanvas.move(self.id, self.MovementAmount, 0)

__init__(self,Canvas,Position,Color,MovementAmount)

This is a function that "constructs" a new "object" from the definition of the class. The "self" parameter is a "pointer" to the new object. The function first saves the "Canvas" and "Coordinate" parameters into itself for access later on. The function then creates an "oval" object and adds it to the Canvas.

You can add varaibles to the object with code like "self.MovementAmount=MovementAmount". This will take the value passed in as MovementAmount and save it in the object with the label "MovementAmount".

move(self)

This function moves the objects based on the MovementAmount. The concept is that this function should be called for a single time step so the animal can move a given distance.

3. Calling The Blob

The code below shows you how to use the Blob class to make a number of blobs move across the screen. The code:

  1. Imports the required libraries
  2. Sets up the tkinter interface
  3. Creates the canvas that the blobs will move around on
  4. Initializes the Blobs into a list
  5. Runs "forever" while updating the blobs positions and then allowing tkinter to redraw the window. This step includes:
    1. Move each blob in the list
    2. Call "root.update_idletasks()" to allow the window to redraw
    3. Call "time.sleep()" to slow down the speed of the animation
#################################################################
# A script to create and move Blobs in a tKinter frame
# Heavliy modified from: http://effbot.org/tkinterbook/canvas.htm
# Author: Jim Graham
# Date: 2/27/2013
#################################################################
from Tkinter import *
from Blob import Blob
import time # bring in the time library so we can "wait" between drawing

# Setup the GUI with a modeless window labeled "Blobs"
root = Tk()
root.title("Blobs")
root.resizable(0, 0)

# Create the Canvas widget for the blobs to move in
canvas = Canvas(root, width=500, height=500, bd=0, highlightthickness=0)
canvas.pack()

# Create four blobs objects
TheItems = [
Blob(canvas, (100, 50), "red", 2),
Blob(canvas, (100, 80), "blue", -1),
Blob(canvas, (100, 120), "green", 1),
Blob(canvas, (100, 150), "gold", -2)
]

root.update() # fix geometry

# Move the blobs forever
try:
	while True:
		for TheItem in TheItems:
			TheItem.move()
		root.update_idletasks() # redraw
		root.update() # process events
		time.sleep(.01)

except TclError:
	pass # to avoid errors when the window is closed

Copy and paste this code into Wing and then try running it. You should see four circles moving in a window. Now try changing the color and size of the blobs. Try changing the sleep parameter speed up and slow down the action. Try adding more blobs.

You can now add additional movement in the vertical direction, add interactions between blobs, make the blobs grow, breed, and die - the options are limitless!

Additional Resources:

Python Documentation: Classes

An Introduction to tkinter