CS 240: Data Structures and Algorithms
James Madison University, Fall 2012

In-Class Activity #3: Object Oriented Python

Objectives

The goal of today's activity is to get comfortable working with object oriented features of Python by implementing a class hierarchy.

Resources

Everything you need to know to complete today's activity is covered in appendix D of our textbook. The section on Classes in the Python tutorial is also quite clear.

Exercises

  1. Create a new Python file, and add a main function for testing the Classes that you will create below. Don't forget to include a call to main.
  2. Implement the class hierarchy described by the UML diagram below. Before you start programming, think carefully about which data attributes and methods should be defined in which classes, and how best to take advantage of inheritance. Test your code as you work.



    Notes:
    • The colons in the diagram above are used to indicate types. xPos(): float indicates that the xPos method will return a floating point number. contains(x:float,y:float): boolean indicates that the contains method expects two floating-point parameters and returns a boolean.
    • Colors are represented by their names. The turtle graphics package recognizes the same set of names as the Tk package.
    • The xPos and yPos functions return the of the lower-left corner of a rectangle, and the center of a circle.
    • In Python it is necessary to explicitly call the constructor of the superclass in the the constructor of the subclass. The syntax is:
      super(SubClassName,self).__init__(args)
      Where SubClassName is the name of the subclass, and args represents the arguments expected by the constructor of the superclass (excluding self).
    • For the time being, feel free to implement draw textually:
      >>> c = Circle(0.0, 0.0, 50.0, "red")
      >>> c.draw()
      red Circle with radius 50.0 drawn at position (0.0, 0.0).

Finishing Up

There is nothing to hand in for this assignment. Make sure that you save a copy of your code, either on a thumb drive, the N: drive, or by e-mailing it to yourself. If you worked with a partner, make sure both of you get a copy.