संभव डुप्लिकेट:
What is the difference between @staticmethod and @classmethod in Python?पायथन स्टेटिक तरीकों, क्यों?
मैं कक्षाओं में staticmethods के बारे में कुछ प्रश्न हैं। मैं एक उदाहरण देकर शुरू करूंगा।
उदाहरण एक:
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
उदाहरण दो:
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 फोन नहीं कर सकते हैं, मैं सिर्फ सच में जब और यह कारण है कि उपयोग करने के लिए यकीन नहीं है। मेरे मन में, यदि आप कुछ जिम्मेदार ठहराया के साथ एक वर्ग बनाने के लिए, शायद आप उन्हें बाद में उपयोग करने के लिए, और एक staticmethod जहां सभी विशेषताओं प्रतिदेय नहीं कर रहे हैं नहीं चाहते हैं। कोई भी मुझे यह समझा सकता है? पायथन मेरा पहला प्रोग्रामिंग लैंगंज है, इसलिए यदि जावा में यह वही है उदाहरण के लिए, मुझे नहीं पता।
बंद करने के लिए वोट करने के लिए नफरत है, लेकिन सवाल मैं करने के लिए लिंक करने के बाद में जवाब काफी अच्छा कर रहे हैं। ध्यान दें कि '@ classmethod' जावा' स्थिर 'के समान है। '@ staticmethod' बहुत बेकार है। –
धन्यवाद जोश, शायद मैंने ठीक से खोज नहीं की है, लिंक के लिए धन्यवाद, अब जांच करेगा –