Create a method display() that display the length, width, perimeter and area of an object created using an instantiation on rectangle class.
Question
Create a method display() that display the length, width, perimeter and area of an object created using an instantiation on rectangle class.
Solution
Sure, here is a Python method that fits your description:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def display(self):
perimeter = 2 * (self.length + self.width)
area = self.length * self.width
print(f"Length: {self.length}")
print(f"Width: {self.width}")
print(f"Perimeter: {perimeter}")
print(f"Area: {area}")
# Create an object of Rectangle
rect = Rectangle(5, 10)
# Call the display method
rect.display()
In this code:
-
We define a class
Rectanglewith an__init__method that takeslengthandwidthas parameters. These parameters are stored as instance variables. -
We define a
displaymethod within theRectangleclass. This method calculates theperimeterandareaof the rectangle using the formulae2 * (length + width)andlength * widthrespectively. It then prints thelength,width,perimeter, andarea. -
We create an instance of the
Rectangleclass withlength5 andwidth10, and store it in the variablerect. -
We call the
displaymethod on therectobject, which prints thelength,width,perimeter, andareaof the rectangle.
Similar Questions
Write a VB Program that calculates the area of a rectangle give that the area = lengthmultiplied by width.
The perimeter of a rectangle is units. Its width is units.Write an equation to determine the length of the rectangle.
The difference between the length and breadth of a rectangle is 23 m. If its perimeter is 206 m, then its area is:1520 m22420 m22480 m22520 m2
A rectangle has perimeter 12 m. Express the area A of the rectangle as a function of the length, L, of one of its sides.
The dimensions, in centimetres, of this rectangle are shown as algebraic expressions.Work out the length and width of the rectangle.(6 marks)
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.