staticmethod()內(nèi)置函數(shù)為給定函數(shù)返回靜態(tài)方法。
staticmethod()的語法為:
staticmethod(function)
使用staticmethod()被認(rèn)為是創(chuàng)建靜態(tài)函數(shù)的非Python標(biāo)準(zhǔn)方式。
因此,在較新版本的Python中,您可以使用@staticmethod裝飾器。
@staticmethod的語法為:
@staticmethod def func(args, ...)
staticmethod()方法采用單個(gè)參數(shù):
function -需要轉(zhuǎn)換為靜態(tài)方法的函數(shù)
staticmethod()對于作為參數(shù)傳遞的函數(shù),返回靜態(tài)方法。
靜態(tài)方法與類方法非常相似,是綁定到類而不是對象的方法。
他們不需要?jiǎng)?chuàng)建類實(shí)例。因此,它們不依賴于對象的狀態(tài)。
靜態(tài)方法和類方法之間的區(qū)別是:
靜態(tài)方法對類一無所知,只處理參數(shù)。
類方法與類一起使用,因?yàn)槠鋮?shù)始終是類本身。
可以通過類及其對象來調(diào)用它們。
Class.staticmethodFunc() or even Class().staticmethodFunc()
class Mathematics:
def addNumbers(x, y):
return x + y
# 創(chuàng)建addNumbers靜態(tài)方法
Mathematics.addNumbers = staticmethod(Mathematics.addNumbers)
print('總數(shù)是:', Mathematics.addNumbers(5, 10))輸出結(jié)果
總數(shù)是: 15
靜態(tài)方法的有使用限制,因?yàn)榕c類方法或類中的任何其他方法一樣,靜態(tài)方法無法訪問類本身的屬性。
但是,當(dāng)您需要一個(gè)不訪問類的任何屬性但知道它屬于該類的實(shí)用程序函數(shù)時(shí),我們將使用靜態(tài)函數(shù)。
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
return self.date
@staticmethod
def toDashDate(date):
return date.replace("/", "-")
date = Dates("15-12-2016")
dateFromDB = "15/12/2016"
dateWithDash = Dates.toDashDate(dateFromDB)
if(date.getDate() == dateWithDash):
print("Equal")
else:
print("Unequal")輸出結(jié)果
Equal
在這里,我們有一個(gè)Dates僅適用于帶破折號(-)的日期的類。但是,在我們以前的數(shù)據(jù)庫中,所有日期都以斜杠表示。
為了將斜線日期轉(zhuǎn)換為帶破折號(-)日期,我們創(chuàng)建了一個(gè)效用函數(shù)toDashDate中Dates。
這是靜態(tài)方法,因?yàn)樗恍枰L問Dates自身的任何屬性,而只需要參數(shù)。
我們也可以在toDashDate類外創(chuàng)建,但是由于它僅適用于日期,因此將其保留在Dates類內(nèi)是合乎邏輯的。
當(dāng)我們不希望類的子類更改/重寫方法的特定實(shí)現(xiàn)時(shí),可以使用靜態(tài)方法。
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
return self.date
@staticmethod
def toDashDate(date):
return date.replace("/", "-")
class DatesWithSlashes(Dates):
def getDate(self):
return Dates.toDashDate(self.date)
date = Dates("15-12-2016")
dateFromDB = DatesWithSlashes("15/12/2016")
if(date.getDate() == dateFromDB.getDate()):
print("Equal")
else:
print("Unequal")輸出結(jié)果
Equal
在這里,我們不希望DatesWithSlashes子類覆蓋靜態(tài)實(shí)用程序方法toDashDate,因?yàn)樗挥幸粋€(gè)用途,即將date更改為dash-date。
通過重寫getDate()子類中的方法,我們可以輕松地利用靜態(tài)方法來發(fā)揮自己的優(yōu)勢,從而使其與DatesWithSlashes類一起正常工作。