Python staticmethod() 函數用於將函數轉換為靜態函數。靜態方法是屬於類而不是類的實例的方法。靜態方法不需要實例化。
用法:staticmethod(function)
參數:
staticmethod() 方法采用單個參數,即它采用函數作為參數。
返回值:
staticmethod() 返回作為參數傳遞的函數的靜態方法。
範例1:staticmethod()的應用實現
Python3
class demoClass:
def greet(msg):
return msg
# convert the add to a static method
demoClass.greet = staticmethod(demoClass.greet)
# we can access the method without
# creating the instance of class
print(demoClass.greet("hai"))
輸出:
hai
在上麵的代碼中,創建了一個方法為 greet() 的類,然後將其轉換為使用 staticmethod() 的靜態方法,並且在不創建實例的情況下調用它,正如我們前麵討論的那樣,不需要創建類的實例來調用一種靜態方法。
範例2:staticmethod()的應用實現
Python3
class demoClass:
def __init__(self, a, b):
self.a = a
self.b = b
def add(a, b):
return a+b
def diff(self):
return self.a-self.b
# convert the add to a static method
demoClass.add = staticmethod(demoClass.add)
# we can access the method without creating
# the instance of class
print(demoClass.add(1, 2))
# if we want to use properties of a class
# then we need to create a object
Object = demoClass(1, 2)
print(Object.diff())
輸出:
3 -1
如果我們不需要使用類屬性,那麽我們可以使用靜態方法,在上麵的代碼中,add() 方法不使用任何類屬性,因此使用 staticmethod() 將其設置為靜態,並且需要通過創建實例來調用 diff 方法因為它使用類屬性。
相關用法
注:本文由純淨天空篩選整理自mohan1240760大神的英文原創作品 Python staticmethod() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。