thể trùng lặp:
What is the difference between @staticmethod and @classmethod in Python?Python Phương pháp tĩnh, tại sao?
Tôi có một số câu hỏi về staticmethods trong các lớp học. Tôi sẽ bắt đầu bằng cách đưa ra một ví dụ.
Ví dụ một:
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()
Đầu ra:
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
Ví dụ hai:
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.
Đầu ra
Hello Ephexeve M, your age is 18
Tôi thấy tôi không thể gọi bất kỳ self.attribute trong một staticmethods, tôi chỉ không thực sự chắc chắn khi nào và tại sao để sử dụng nó. Trong tâm trí của tôi, nếu bạn tạo ra một lớp học với một vài quy, có lẽ bạn muốn sử dụng chúng sau này, và không có một staticmethod nơi tất cả các thuộc tính không thể gọi được. Bất cứ ai cũng có thể giải thích cho tôi điều này? Python là ngôn ngữ lập trình đầu tiên của tôi, vì vậy nếu điều này giống nhau trong Java chẳng hạn, tôi không biết.
Ghét để bỏ phiếu để đóng, nhưng câu trả lời trong câu hỏi tôi đã liên kết là khá tốt. Lưu ý rằng '@ classmethod' tương tự như javas' static'. '@ staticmethod' khá là vô ích. –
Cảm ơn Josh, có lẽ tôi đã không tìm kiếm đúng cách, nhờ liên kết, sẽ kiểm tra ngay bây giờ –