Olası Çoğalt: Python Statik yöntemler, neden?
What is the difference between @staticmethod and @classmethod in Python?
örnek:
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()
Çıkışlar:
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
örnek:
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.
Çıkışlar
Hello Ephexeve M, your age is 18
Görünüşe göre, herhangi bir self.attribute'u bir staticmethods içinde arayamıyorum, ne zaman ve neden kullanmak gerektiğinden emin değilim. Aklımda, atfedilen bir sınıfı oluşturursanız, belki de bunları daha sonra kullanmak istersiniz ve tüm özniteliklerin kalıcılığının olmadığı bir statik yöntem bulunmaz. Bunu herkes anlatabilir mi? Python benim ilk programlama langungumdur, bu yüzden eğer Java'da aynıysa, bilmiyorum. Bunu staticmethod
elde etmek çalıştığımız şey
kapatmak için oy verme istemem ama bağladıysanız söz konusu cevapları oldukça iyidir. Not @ classmethod 'javas' statik 'benzer. @ staticmethod 'oldukça işe yaramaz. –
Teşekkürler Josh, belki de düzgün aramadım, bağlantı için teşekkürler, şimdi kontrol edecek –