Difference between @staticmethod and a function inside a method

Which are the differences or advantages of Circle1 and Circle2? Is there a more correct way than the other? The only advantage is that in Circle2 I can inherit it?

class Geometry(object):
    def __init__(self, x, y):
        self.ptsx = x
        self.ptsy = y
        
        
class Circle1(Geometry):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        def circle_formula(radius):
            return 3.14*radius
        
        return circle_formula(self.radius)
    
    
class Circle2(Geometry):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return self.circle_formula(self.radius)   
    
    @staticmethod
    def circle_formula(radius):
            return 3.14*radius

I know that the correct way would be that the @staticmethod of Cicle2 would be a function like area_formula and when inheriting it, rewrite it. But my doubt is, if I really have to use an auxiliary function that only is going to live inside a specific class, what is the most correct way to implement it?

Upvotes: 0

Views: 78

Answers (1)

mathiasminacapilli
mathiasminacapilli

Reputation: 33

The main difference between those two classes, is that, if you add staticmethod to a method, you can access to that method without instantiating the class.

I mean, I could do: Circle2.circle_formula(2).

In Circle1, you should instantiate the class to access to the method to calculate the area;

my_circle = Circle1(2)
my_circle.area()

But, in the case that you are presenting, I would add the logic inside the area method, as the Circle1 is implemented, without using a function inside of it. Like this:

class Circle1(Geometry):
    def __init__(self, radius):
        self.radius = radius
    def area(self):        
        return 3.14*radius

Upvotes: 1

Related Questions