staticmethod()
用於創建靜態函數。靜態方法不綁定到對象,它綁定到類。這意味着,如果對象沒有綁定到靜態方法,則靜態方法不能修改對象的狀態。
使用staticmethod()
的語法。
**staticmethod (function)** #Where function indicates function name
為了在類中定義靜態方法,我們可以使用內置的 decorator @staticmethod。當函數用@staticmethod 修飾時,我們不傳遞類的實例。這意味着我們可以在類中編寫一個函數,但是不能使用該類的實例。
使用@staticmethod 裝飾器的語法。
**@staticmethod
def func(args, ...)** #Where args indicates function parameters
staticmethod()
參數:
只接受一個參數。參數通常是需要轉換為靜態的函數。我們也可以使用效用函數作為參數。
參數 | 描述 | 必需/可選 |
---|---|---|
功能 | 作為靜態方法創建的函數的名稱 | 需要 |
staticmethod()
返回值
它以靜態方法返回給定的函數
| 投入 | 返回值 |
| 功能 | 給定函數的靜態方法 |
Python 中staticmethod()
的示例
示例 1:使用staticmethod()
創建一個靜態方法
class Mathematics:
def Numbersadd(x, y):
return x + y
# create Numbersadd static method
Mathematics.Numbersadd= staticmethod(Mathematics.Numbersadd)
print('The sum is:', Mathematics.Numbersadd(20, 30))
輸出:
The sum is: 50
示例 2:繼承如何與靜態方法一起工作?
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("20-04-2021")
dateFromDB = DatesWithSlashes("20/04/2021")
if(date.getDate() == dateFromDB.getDate()):
print("Equal")
else:
print("Unequal")
輸出:
Equal
示例 3:如何創建實用函數的靜態方法?
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
return self.date
@staticmethod
def toDashDate(date):
return date.replace("/", "-")
date = Dates("12-03-2020")
dateFromDB = "12/03/2020"
dateWithDash = Dates.toDashDate(dateFromDB)
if(date.getDate() == dateWithDash):
print("Equal")
else:
print("Unequal")
輸出:
Equal
原創文章,作者:Q3O4G,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/128463.html