Answer to Question #319452 in Python for anshika nigam

Question #319452

Create a class named 'Rectangle' with two data members- length and

breadth and a function to calculate the area which is 'length*breadth'. The

class has three constructors which are :

1 - having no parameter - values of both length and breadth are assigned

zero.

2 - having two numbers as parameters - the two numbers are assigned as

length and breadth respectively.

3 - having one number as parameter - both length and breadth are

assigned that number.

Now, create objects of the 'Rectangle' class having none, one and two

parameters and print their areas.


1
Expert's answer
2022-03-28T08:03:46-0400
class Rectangle:
    def __init__(self, length=None,  breadth=None):
        if length is None:
            self._length =  0
            self._breadth = 0
        else:
            self._length = length
        if breadth is None:
            self._breadth = self._length
        else:
            self._breadth = breadth

    def area(self):
        return self._length * self._breadth


def main():
    r1 = Rectangle()
    r2 = Rectangle(1)
    r3 = Rectangle(1, 2)

    print('The area of the rectangle r1 is', r1.area())
    print('The area of the rectangle r2 is', r2.area())
    print('The area of the rectangle r3 is', r3.area())

if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS