CS 115 Lab 12, Part A: Classes

[Back to lab instructions]

Refer to the Week 14 reading or other resources as necessary to complete this part.


Classes and objects

  1. Enter the following code into the online Python 3 tutor:
    class Rectangle:
        def __init__(self, L, W):
            self.set_length(L)
            self.set_width(W)
    
        def set_width(self, W):
            self.width = W
    
        def set_length(self, L):
            self.length = L
    
        def get_width(self):
            return self.width
    
        def get_length(self):
            return self.length
    
        def get_area(self):
            return self.get_length() * self.get_width()
    
    # STOP HERE
    # This code uses the Rectangle class
    r1 = Rectangle(1, 2) # Statement 1
    r2 = Rectangle(5, 6) # Statement 2
    a1 = r1.get_area() # Statement 3
    a2 = r2.get_area() # Statement 4
    
  2. Step through the code, stopping at the labeled comment (when the red arrow gets to line 23). Notice how the code above the comment sets up the definition of the Rectangle class and its methods. Answer Question 1 in your writeup.
  3. Step through the complete execution of Statement 1, stopping when the red arrow gets to line 24. Notice that the stacks on the right-hand side of the screen grow downward, so that the current function call and the newly created objects are always at the bottom.
  4. Answer Question 2 in your writeup.
  5. Step through the complete execution of Statement 2, and answer Question 3 in your writeup.
  6. Step through the complete execution of Statements 3 and 4, and answer Question 4 in your writeup
  7. Modify the definition of the Rectangle class to add a get_perimeter method. This method should return the perimeter of the rectangle. Then add a statement to the end of the program to test your new method.
  8. Demo your new method to an instructor. As part of the demo, you will be asked to step through the entire program and answer questions about how it works.
  9. Continue to Part B.