가능한 중복 : Python Static methods, 이유가 무엇입니까?
What is the difference between @staticmethod and @classmethod in Python?
일례 :
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()
출력 :
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
예 2 :
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.
출력
Hello Ephexeve M, your age is 18
staticmethods에서 self.attribute를 호출 할 수 없다는 것을 알았습니다. 언제, 왜 사용해야하는지 잘 모르겠습니다. 내 생각에 몇 가지 속성을 가진 클래스를 만드는 경우 나중에 해당 속성을 사용하고 모든 속성을 호출 할 수없는 정적 메서드가 필요하지 않을 수 있습니다. 누구든지이 사실을 설명 할 수 있습니까? 파이썬이 저의 첫 프로그래밍 언어입니다. 예를 들어 이것이 자바에서 동일하다면, 저는 잘 모릅니다.
투표 마감에 싫지만, 내가 링크 한 질문의 대답은 상당히 좋습니다. '@ classmethod'는 javas'static'과 비슷합니다. '@ staticmethod'는 꽤 쓸모가 없습니다. –
감사합니다. Josh, 아마도 내가 제대로 검색하지 않았으므로 링크를 이용해 주셔서 감사합니다. –