pythonclassinheritance

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

  • 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