Eventuali duplicati:
What is the difference between @staticmethod and @classmethod in Python?Metodi statici Python, perché?
ho alcune domande su staticmethods nelle classi. Inizierò dando un esempio.
Esempio uno:
class Static:
def __init__(self, first, last):
self.first = first
self.last = last
self.age = randint(0, 50)
def printName(self):
return self.first + self.last
@staticmethod
def printInfo():
return "Hello %s, your age is %s" % (self.first + self.last, self.age)
x = Static("Ephexeve", "M").printInfo()
Uscite:
Traceback (most recent call last):
File "/home/ephexeve/Workspace/Tests/classestest.py", line 90, in <module>
x = Static("Ephexeve", "M").printInfo()
File "/home/ephexeve/Workspace/Tests/classestest.py", line 88, in printInfo
return "Hello %s, your age is %s" % (self.first + self.last, self.age)
NameError: global name 'self' is not defined
Esempio due:
class Static:
def __init__(self, first, last):
self.first = first
self.last = last
self.age = randint(0, 50)
def printName(self):
return self.first + self.last
@staticmethod
def printInfo(first, last, age = randint(0, 50)):
print "Hello %s, your age is %s" % (first + last, age)
return
x = Static("Ephexeve", "M")
x.printInfo("Ephexeve", " M") # Looks the same, but the function is different.
uscite
Hello Ephexeve M, your age is 18
Vedo che non posso chiamare alcun self.attribute in un metodo statico, non sono proprio sicuro di quando e perché usarlo. Nella mia mente, se crei una classe con pochi attributi, forse li vuoi usare in seguito, e non hai un metodo statico in cui tutti gli attributi non sono richiamabili. Chiunque può spiegarmi questo? Python è la mia prima lingua di programmazione, quindi se questo è lo stesso in Java, ad esempio, non lo so.
L'odio per votare per chiudere, ma le risposte nella domanda che ho collegato sono abbastanza buone. Si noti che '@ classmethod' è simile a java' static'. '@ staticmethod' è praticamente inutile. –
Grazie Josh, forse non ho cercato correttamente, grazie per il link, controlleremo ora –