CS 152: Lab 7

Title image Project 7
Fall 2016

Lab Exercise 7: Classes

The purpose of this lab is to introduce you to the concept of a class and give you practice in creating one.

This is the third part of a three-part project where we'll be simulating the elephant population in Kruger National Part, South Africa. This week we'll be focusing on re-writing the code to use classes. We'll create one Elephant class and one Simulation class.


If you have not already done so, mount your personal space, create a new Project7 folder and bring up TextWrangler and a Terminal. Then download the file elephant-template.py and rename it to elephant.py.

  1. Note that the template gives you the outline of an Elephant class. By convention, class names are capitalized. The first thing to do is to write the __init__ method. This should look a lot like the newElephant function you write two weeks ago. The difference is that you are able to store the elephant's attributes in fields (variables in the self symbol table) and don't have to use a list.

    Once you have finished the __init__ method, run elephant.py to test it. You should see the attributes of 20 elephants printed, and three of them should be pregnant. If you put a print statement into the Elephant.__init__ method, you should see 20 lines of output in the Terminal.

  2. Create the various "get" (accessor) methods described in the template. Each of these methods should return the current value of the specified attribute. For example, the method getAge(self) should return self.age. When you finish these four methods, add code to the test function below to make sure they are working properly. Something like

    print "age: ", e.getAge()

    would work well inside the for loop in the test function.

  3. Create the various evaluation methods. These include things like isFemale or isPregnant. These methods should return True if their attribute matches the query, otherwise False. The code shows the isFemale example. Similarly, isPregnant should return True if self.pregnant is not 0.

    Add some code to your test function that uses these methods. Something like following, inside the for loop, works well.

    print "isFemale: ", e.isFemale()

  4. Next, create methods for setting each attribute. An example is again provided for age: setAge(self, a). Each setting method will take self and then a value as the argument.

    Add code to your test function that uses the "set" (mutator) methods to change a value and then prints it out. Something like the following, inside the for loop, works well.

      e.setAge( 25 )
      print "set age to ", e.getAge()
  5. Finally, make the last three methods, which help the simulation to run by modifying the elephant attributes appropriately. After writing each method, add code to the test function that checks if they are working properly.

When you are done with the lab exercises, you may begin the project.