42.9k views
13 votes
Implement a class named Rectangle. The class should contain:

1. Two data attributes of type float named width and height that specify the width and the height of the rectangle.
2. A constructor that creates a rectangle with the specified width and height. If no argument is provided, it should use 1.0 for both values. If any input value is negative, the function should raise an exception.
3. Functions get_width and get_height that return the corresponding value
4. The set_width and set_height function that update the values if and only if the input is positive; otherwise do nothing
5. Functions get_area and get_perimeter that return the area and the perimeter of this rectangle respectively.
6. A function rotate that swaps the height and width of a rectangle object.
7. A class variable count that keeps track of the number of rectangles created so far.
8. A class method get_count that returns the above value.
9. An equality operator that returns True if and only if the two rectangles are of the same shape.
10. A __str__ function that returns the information of this rectangle in some readable format.

1 Answer

5 votes

Answer:

Step-by-step explanation:

The following code is written in Python and creates a Rectangle class that performs all the necessary functions mentioned in the question...

from itertools import count

class Rectangle():

_ids = count(0)

width = 1.0

height = 1.0

def __init__(self, width, height):

if (width < 0) or (height < 0):

raise Exception("Sorry, no numbers below zero")

else:

self.id = next(self._ids)

self.width = width

self.height = height

def get_width(self):

return self.width

def get_height(self):

return self.height

def set_width(self, width):

if width > 0:

self.width = width

def set_height(self, height):

if height > 0:

self.height = height

def get_area(self):

return (self.height * self.width)

def get_perimeter(self):

return ((self.height * 2) + (self.width * 2))

def rotate(self):

temp = self.height

self.height = self.width

self.width = temp

def get_count(self):

return self._ids

def equality(self, rectangle1, rectangle2):

if rectangle1 == rectangle2:

return True

else:

return False

def __str__(self):

return 'Rectangle Object with Height: ' + str(self.height) + ' and Width: ' + str(self.width)

User Curtis Olson
by
5.6k points