8
Are there any static methods in Python? If there are any how do I make a static method?
8
Are there any static methods in Python? If there are any how do I make a static method?
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.
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 python
You are not signed in. Login or sign up in order to post.
In case it would be
Cachorro.som_de_latido()
orcachorro.som_de_latido()
, even ?– MagicHat
In which cases? With the decorator?
– vinibrsl
You say, "You can call it like
cachorro.som_de_latido()
", can be that way or should beCachorro.som_de_latido()
?– MagicHat
In the first example, with
staticmethod
, utilizeClasse.funcao()
(Cachorro.som_de_latido()
). In the second example, setting the function outside the class, usearquivo.funcao()
(cachorro.som_de_latido()
)– vinibrsl
Um, that’s what I wasn’t understanding, not that I understood, but it’s clear
– MagicHat
Thanks buddy, you’ve helped me a lot!
– Matheus Grossi