Powiel możliwe:
What is the difference between @staticmethod and @classmethod in Python?Python Metody statyczne, dlaczego?
Mam kilka pytań dotyczących staticmethods w klasach. Zacznę od podania przykładu.
Przykład pierwszy:
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()
Wyjścia:
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
Przykład drugi:
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.
Wyjścia
Hello Ephexeve M, your age is 18
Widzę, że nie mogę nazwać żadnego self.attribute w staticstars, po prostu nie jestem pewien, kiedy i dlaczego go użyć. Moim zdaniem, jeśli utworzysz klasę z kilkoma przypisanymi, być może będziesz chciał użyć ich później i nie będziesz miał metody statycznej, w której wszystkie atrybuty nie będą dostępne. Ktoś może mi to wyjaśnić? Python jest moim pierwszym programistycznym langunge, więc jeśli jest taki sam w Javie, na przykład, nie wiem.
Nienawidzę głosować, aby zamknąć, ale odpowiedzi w pytaniu, do którego dodałem, są całkiem dobre. Zwróć uwagę, że '@ classmethod' jest podobne do javas' static'. '@ staticmethod' jest praktycznie bezużyteczne. –
Dzięki Josh, może nie przeszukaliśmy poprawnie, dzięki za link, sprawdzi teraz –