Are there static methods in Python?

Asked

Viewed 971 times

8

Are there any static methods in Python? If there are any how do I make a static method?

2 answers

12


Use the decorator @staticmethod:

class Classe(object):
    @staticmethod
    def funcao(arg1, arg2):
        pass

that code produces:

class Classe():
    def funcao(arg1, arg2):
        pass

funcao = staticmethod(funcao)

can call your method so:

Classe.funcao(arg1, arg2)

See more about the built-in function staticmethod(function) in documentation. And the source code - in C.

If you don’t want to use the decorator, another way to achieve this is declaring the function outside the class. Assuming you have the cachorro.py:

class Cachorro(object):
    def __init__(self, nome):
        self.nome = nome

    def latir(self):
        if nome = "Ted":
            return som_de_latido()
        else:
            return "woof woof!"

def som_de_latido():
    return "au au!"

In the above code the function som_de_latido() plays a role in a static function. You can call it like cachorro.som_de_latido(). It’s different from the decorator because there you call as arquivo.Classe.funcao() and here is arquivo.funcao().

By choosing to do outside the class you are not creating a static method of truth, only achieving a similar implementation. I quoted just because it’s possible.

  • In case it would be Cachorro.som_de_latido() or cachorro.som_de_latido(), even ?

  • In which cases? With the decorator?

  • You say, "You can call it like cachorro.som_de_latido() ", can be that way or should be Cachorro.som_de_latido()?

  • In the first example, with staticmethod, utilize Classe.funcao() (Cachorro.som_de_latido()). In the second example, setting the function outside the class, use arquivo.funcao() (cachorro.som_de_latido())

  • Um, that’s what I wasn’t understanding, not that I understood, but it’s clear

  • Thanks buddy, you’ve helped me a lot!

Show 1 more comment

7

Using the @staticmethod:

class Exemplo(object):
    @staticmethod
    def soma(x,y):
        return x+y
    def subtrai(x,y):
        return x-y

print(Exemplo.soma(2,2));

Browser other questions tagged

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