Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the language python: (The rectangle class) design a class named rectangle to

ID: 3855637 • Letter: I

Question

In the language python:

(The rectangle class) design a class named rectangle to represent a rectangle. The class contains:

-Two data field named width and height

-a constructor that creates a rectangle with a specified width and height. The default values 1 and 2 for the width and height, respectively

-a method named getArea() that returns the area of this rectangle

-a method named getPerimeter() that returns the perimenter

-Define width and height as private data fields of the class

-Include the public methods getWidth( ) and getHeight( ) in the class

Test these functions with calls from main( ) for the two given data sets

when the user enter input like 4 and 40 the output should look like this" A 4 x 40 rectangle has an area of 160 and a perimeter of 88."

have the output print to one decimal place

All four numbers in bold above should be produced by appropriate function calls to the getter methods of the class.

Explanation / Answer

class rectangle has been defined with a constructor that creates a rectangle with a specified width and height. The default values 1 and 2 must be given in the same costructor as shown, as unlike java and Cpp, multiple constructors are not supported. A method named getArea() that returns the area of this rectangle by multiplying width X height

A method named getPerimeter() that returns the perimeter by 2 X (Width + Height)

main( ) calls rectanlgle a for 4 and 40 values and also for another rectangle b which has decimal point 5.1 as width and 7.0 as height.

There are no private variables directly supported in Python, however with __ prefix similar result can be achieved.

Python program

class Rectangle:
def __init__(self, width=1.0,height=2.0):
self.w = width
self.h = height
def getPerimeter(self):
return (2 * self.h) + (2 * self.w)
def getArea(self):
return self.h * self.w
def getWidth(self):
return self.w
def getHeight(self):
return self.h

def main():
a = Rectangle(4, 40)
print "Rectangle a has width and height as below"
print "Width: %10.1f"%a.getWidth()
print "Height: %10.1f"%a.getHeight()
print "Area: %10.1f" % a.getArea()
print "Perimeter: %10.1f" %a.getPerimeter()
b = Rectangle(5.1, 7)
print "Rectangle b has width and height as below"
print "Width: %10.1f"%b.getWidth()
print "Height: %10.1f"%b.getHeight()
print "Area: %10.1f" % b.getArea()
print "Perimeter: %10.1f" %b.getPerimeter()
main()

Output

Rectangle a has width and height as below
Width: 4.0
Height: 40.0
Area: 160.0
Perimeter: 88.0
Rectangle b has width and height as below
Width: 5.1
Height: 7.0
Area: 35.7
Perimeter: 24.2

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote