Class and Static Methods - 3 - Hands On

Python >   Python Classes and Objects >   Static Method in python  

Long Question

1741


Answer:

3. Class and Static Methods - 3

1. Define a static method getPi inside Circle which returns the value 3.14. Hint: Use staticmethod decorator.

2. Redefine the area method such that it uses the getPi static method in it.

3. Try accessing the static method by using an object and the class.

4. Check the main/tail section for output handling (read-only).

5. Use the Test against custom input box to output the result for debugging.

6. Provide float values separated by comma (refer test case samples) to display the output/error. • The output should return a key-value pair of the circle number and its corresponding area.

Solution


import os

import sys


#Add circle class implementation here

class Circle(object):

    count = 0

    def __init__(self, radius):

        self.__radius = radius

        Circle.count += 1

    

    @classmethod

    def getCircleCount(self):

        return Circle.count

    

    @staticmethod

    def getPi(self):

        return 3.14

    

    @staticmethod

    def square(x):

        return x**2

    

    def area(self):

        return self.getPi(self.__radius)*self.square(self.__radius)

        

'''Check the Tail section for input/output'''

if __name__ == "__main__":
    with open(os.environ['OUTPUT_PATH'], 'w') as fout:
        res_lst = list()
        circcount = list()
        lst = list(map(lambda x: float(x.strip()), input().split(',')))
        for radi in lst:
            c=Circle(radi)
            res_lst.append(str(c.getCircleCount())+" : "+str(c.area()))
        fout.write("{}".format(str(res_lst)))


This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.