Object Oriented Programming Practice


Below are some practice problems for working with objects in python. These are completely OPTIONAL but are highly recommended as extra practice. Solutions for each can be found at the bottom of the page.

EX00 – Nested Class Environment Diagram

Given the code listing below, draw an environment diagram then answer the questions that follow. In each frame on the stack, remember to include a space for the return address and return value.

The following questions are based on the environment diagram for the code listing. If a question is asked about a name that has not been initalized, respond with undefined.

  1. How many constructor frames have been added to the stack?
  2. From any given Review’s constructor frame, what is the type of self.score?
  3. From biased_average’s frame, what is the type of of the value of self?
  4. From main’s frame, what is the type of alpine.reviews?
  5. What is the printed output of this program once it completes?

EX01 – Vec Class Environment Diagram

Given the code listing below, draw an environment diagram then answer the questions that follow. In each frame on the stack, remember to include a space for the return address and return value.

The following questions are based on the environment diagram for the code listing. If a question is asked about a name that has not been initalized, respond with undefined.

  1. How many Vec objects are on the heap?
  2. From main’s frame, what is the value of a? What is its type?
  3. From main’s frame, what is the value of a.z? What is its type?
  4. From main’s frame, what is the value of x? What is its type?
  5. What is the printed output of this program?

EX02 – Sims

Given the class definition of a Sim provided below, complete the following exercises.

  1. Write a constructor for the Sim class that takes in and sets up the name and age values.
  2. Write a method for the Sim class called bday that increases the Sim’s age by one, turns its is_happy value to True and decreases its hunger value by 30.
  3. Write a function called bday that takes in a Sim and increases its age by one, turns its is_happy to True and decreases its hunger by 30.

Solutions

EX00 – Nested Class Environment Diagram

  1. 3
  2. float
  3. Rating
  4. List[Review]
  5. 8.7

EX01 – Vec Environment Diagram

  1. 2
  2. a is a Vec with the following attributes: x: 1, y: 3, z: -2
  3. a.z is -2. It is a float
  4. undefined.
  5. 1, 5, 0, 0

EX02 – Sims