Posts

Search

Python: Shape Classes with Area Method

Implement two classes:

Rectangle:
The constructor for Rectangle must take two arguments that denote the lengths of the rectangle's sides.
The class must have an area method that returns the area of the rectangle.

Circle:
The constructor for Circle must take one argument that denotes the radius of the circle.
The Circle class must have an area method that returns the area of the circle. To implement the area method, use a precise Pi value, preferably the constant math.pi.

SOLUTION :

import math
import os
import random
import re
import sys


class Rectangle:
     def __init__(self, a=0.0,b=0.0):
        self.a = a
        self.b = b 
     def area(self):
        return self.a * self.b
    
class Circle:
     def __init__(self, radius=0.0):
        self.radius = radius 

     def area(self):
        return self.radius**2*math.pi
        #return self.radius * self.radius * 3.14
    
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    q = int(raw_input())
    queries = []
    for _ in xrange(q):
        args = raw_input().split()
        shape_name, params = args[0], map(int, args[1:])
        if shape_name == "rectangle":
            a, b = params[0], params[1]
            shape = Rectangle(a, b)
        elif shape_name == "circle":
            r = params[0]
            shape = Circle(r)
        else:
            raise ValueError("invalid shape type")
        fptr.write("%.2f\n" % shape.area())
    fptr.close()