[Edu-sig] Best approach to teaching OOP and graphics

Kirby Urner urnerk at qwest.net
Mon Mar 21 18:18:25 CET 2005

> in fact, I feel there may be a risk of the students developing 
> an idea of OOP and graphical programming being two different 
> things if they are introduced separately.

In my book, OOP and graphical programming *are* two different things.

To introduce OOP is to introduce the syntax for classes and forming 
objects from them e.g.

class Foo:

myobj = Foo()

OOP includes ideas of methods & attributes, inheritance, dot notation,
operator overloading, method overriding, constructors, static and class
methods, various design patterns.

You can do all that (or a subset of that) in IDLE if you like.

My approach when introducing classes and objects is to emphasize we've been
using objects all along, e.g. every list object has all these useful methods
by virtue of being of the list type.  I do stuff like:

  >>> dir([]) # spill the guts of an empty list

or even

  >>> dir(1) # spill the guts of the number 1

to show all the "hidden knowledge" any Python object has, owing to the
apparatus of built-in types behind it.  Then the idea is:  as the
programmer, you're free to *extend* the tool box with new types (i.e.
classes) of your own design.  These might have to do with GUI programming in
some way, but they certainly don't have to.  The first classes I introduce
look like this:

import random
from random import randint

class Animal:

	 def __init__(self, name):
		  self.name = name
		  self.state = 'Awake'

	 def sleep(self):
		  print "Zzzzzzz..."
		  self.state = 'Sleeping'

	 def eat(self, food):
		  print "I am eating %s" % (food)

	 def wakeup(self):
		  self.state = 'Awake'

	 def pain(self, location, amount): # <-- student contribution
		  print "My %s hurts!" % (location)
		  self.state = 'In pain'
		  print "It hurts %s!" % (amount)

class Dog(Animal):

	def bark(self, times):
		print "Woof woof! " * times

	def jump(self, object):  # <-- one of my students wrote this method
		fallchance = randint(1,10)
		if fallchance == 10:
			print "I tripped over a %s!" % (object)
			self.pain('head', 'a lot')
                if fallchance != 10:
                        print "I jumped over a %s." % (object)

The fact that OOP has proved especially useful when it comes to GUI
programming is very true, but then that's all the more reason to not confuse
the two.

In my high school level Python classes, I've done quite a bit with OOP, and
with graphics (POV-Ray especially, with a Python front end for generating
scene description language), but to date I have never yet taught any GUI or
widget programming.  

John Zelle's Tkinter-based graphics.py is an attractive option, if I *do*
start getting into teaching that stuff.  It's easy to use and gives the
right idea, but without getting too complicated too quickly.


More information about the Edu-sig mailing list