Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How change radius in python inheritance

I want to get radius of a circle with other area of the circle. I get right new area, but not right radius. The radius is the same. Why? How can I solve this problem?

import math


class Figure:
    def __init__(self, area):
        self.__area = area

    def set_area(self, area):
        self.__area = area

    def get_area(self):
        return self.__area


class Circle(Figure):
    def __init__(self, area):
        super().__init__(area)
        self.__radius = math.sqrt(self.get_area() / math.pi)

    def get_radius(self):
        return self.__radius


c = Circle(25)
print(c.get_area())
print(c.get_radius())  
c.set_area(100)
print(c.get_area())
print(c.get_radius())  # Here i get the same radius. Why? How can I solve this problem? 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You save the __radius member in the Circle‘s constructor. It’s not recalculated when you set a different area.

One approach is to just not save it, and calculate it on demand:

class Circle(Figure):
    def get_radius(self):
        return math.sqrt(self.get_area() / math.pi)

Alternatively, if you’re getting the radius considerably more frequently than changing the area, and you want to cache it for improved performance, you can recalculate it when you set the area:

class Figure:
    def __init__(self, area):
        self.set_area(area)

    def set_area(self, area):
        self.__area = area

    def get_area(self):
        return self.__area


class Circle(Figure):
    def set_area(self, area):
        super().set_area(area)
        self.__radius = math.sqrt(self.get_area() / math.pi)

    def get_radius(self):
        return self.__radius
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading