Why use static methods in python

6

I am studying on the subject of the title and I can not get the idea with the explanation video and Stk I found, then when and why you use static method @staticmethod in python, there is a positive addition to just do not reference the object with the self % (the question keeps to Closures / Decorators (What I see being widely used (s) in languages with Javascript but in python ...) in such a language?

    
asked by anonymous 12.06.2017 / 21:11

1 answer

12

A static method is a method that can be called without the instance of the class.

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print x

MyClass.the_static_method(2)

It is useful for doing operations within the class, such as an area calculation function. You can have the Circle class and methods that can be called without requiring an instance, since the goal is the calculation:

class Pizza(object):
    def __init__(self, radius, height):
        self.radius = radius
        self.height = height

    @staticmethod
    def compute_area(radius):
         return math.pi * (radius ** 2)

    @classmethod
    def compute_volume(cls, height, radius):
         return height * cls.compute_area(radius)

    def get_volume(self):
        return self.compute_volume(self.height, self.radius)
    
12.06.2017 / 21:24