PYTHON HELP To create a instance of a class, we call the class using the class n
ID: 3571874 • Letter: P
Question
PYTHON HELP
To create a instance of a class, we call the class using the class name and pass all the parameters that the __init__ method accepts except the self attribute. Here you will notice that we only need to name and gpa as the arguments. The self parameter does not need to be included.
student1 = Student("John", 3.5)
student2 = Student("Smith", 3.86)
For this recitation you will creating a class called Shape and add a __init__ method to initialize all the variables to zero, which you will be using in the program. Then add methods to the class called rectangle, triangle and circle which will be used to calculate the areas. These methods should take the necessary parameters to calculate the area and print the area. For circle the parameter should be radius. For triangle, the parameter should be height and base. For rectangle, the parameter should be length and width.
Explanation / Answer
# Shape program in Python
class Shape:
def __init__(self):
self.length = 0
self.width = 0
self.height = 0
self.base = 0
self.radius = 0
# method to calculate the areaOfRectangle
def areaOfRectangle(self, length, width):
area=length*width;
print ("Area of Rectangle is %.2f" % area)
# method to calculate the areaOfTriangle
def areaOfTriangle(self, height, base):
area=0.5*height*base;
print ("Area of Triangle is %.2f" % area)
# method to calculate the areaOfCircle
def areaOfCircle(self, radius):
area=3.14*radius*radius;
print ("Area of Circle is %.2f" % area)
#main method
def main():
shape1= Shape()#constructor which will initialize the value as 0 to all variables
shape1.areaOfRectangle(5,10)#invoking the areaOfRectangle()
shape1.areaOfTriangle(4,5)#invoking the areaOfTriangle()
shape1.areaOfCircle(5)#invoking the areaOfCircle()
main()
-----------output--------
Area of Rectangle is 50.00
Area of Triangle is 10.00
Area of Circle is 78.50
-----------output--------
Note: This python script was compiled in python3
Feel free to ask doubts/question. God bless you
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.