Why use static python methods

Asked

Viewed 3,710 times

7

I’m studying about the subject of the title and I can’t get the idea with the explanation on video and the Stk I found, so when and why we use static method @staticmethod in python, one has some positive point besides simply not referencing the object with the self ( The question holds for Closures / Decorators ( Which I see being widely used ( s ) in Javascript languages but in python ... ) in such language ?

1 answer

13


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

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

MyClass.the_static_method(2)

It is useful to perform operations within the class, such as an area calculation function for example. You can have the Circle class and methods that can be called without the need for instance, because 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)
  • 2

    Do you have a reference so I can study more about @classmethod?

  • 2

    https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods

  • You would know to inform me of the name given to these ' items ' ( Static met Hod, Property, class met Hod ... ) of the language ?

  • 1

    The translation would be static method, class property and method. But if you’re wondering what those @on top of the methods are, this is called a decorator.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.