Exercise 5.5.5: Rectangle class

Exercise 5.5.5: Rectangle class

5 points

Let’s Go!

Write your own accessor and mutator method for the Rectangle class instance variables.

You should create the following methods:

  • getHeight
  • setHeight
  • getWidth
  • setWidth
  • getArea
  • getPerimeter
  • toString- The output of a rectangle with width 10 and height 4 method should be:

Rectangle width: 10, Rectangle height: 4

THE CODEHS ANSWER WITH NO ERRORS PLEASE 

The correct answer and explanation is:

Here is the correct implementation of the Rectangle class with accessor and mutator methods (getHeight, setHeight, getWidth, setWidth), as well as methods to compute the area (getArea), perimeter (getPerimeter), and a toString method.

Explanation (300 words)

The Rectangle class is a blueprint for creating rectangle objects with width and height as instance variables. Here’s how the implementation works:

  1. Constructor (__init__): This initializes the rectangle’s width and height when a new object is created.
  2. Accessor Methods:
    • getHeight returns the rectangle’s height.
    • getWidth returns the rectangle’s width. These methods allow safe and controlled access to private or internal variables.
  3. Mutator Methods:
    • setHeight allows updating the height of the rectangle.
    • setWidth allows updating the width of the rectangle. These methods enable modifications to instance variables while maintaining control and ensuring validations can be added if necessary.
  4. Area and Perimeter:
    • getArea calculates the area by multiplying width by height.
    • getPerimeter calculates the perimeter using the formula 2 * (width + height).
  5. toString Method:
    • This method formats the rectangle’s width and height into a user-friendly string representation.

Advantages:

  • Encapsulation: The class provides controlled access and modification of instance variables.
  • Reusability: The methods can be reused, and the logic for area/perimeter is centralized within the class.
  • Readability: The toString method makes debugging and logging easier.

This implementation is free of errors and adheres to best practices for creating Python classes with accessor and mutator methods.

Scroll to Top