Are there static methods in Python? If they exist how do I make a static method?
Are there static methods in Python? If they exist how do I make a static method?
Use the decorator @staticmethod
:
class Classe(object):
@staticmethod
def funcao(arg1, arg2):
pass
This code produces:
class Classe():
def funcao(arg1, arg2):
pass
funcao = staticmethod(funcao)
You can call your method like this:
Classe.funcao(arg1, arg2)
See more about the built-in staticmethod(function)
function in documentation . And the source code - in C.
If you do not want to use the decorator, another way to accomplish this is declaring the function outside the class. Assuming you have 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 code above the function som_de_latido()
plays the role of a static function . You can call it as cachorro.som_de_latido()
. It is different from the decorator because there you call as arquivo.Classe.funcao()
and here it is arquivo.funcao()
.
By choosing to do outside the class you are not creating a true static method, only achieving a similar implementation. I quoted just because it's possible.
Using @staticmethod :
class Exemplo(object):
@staticmethod
def soma(x,y):
return x+y
def subtrai(x,y):
return x-y
print(Exemplo.soma(2,2));