新聞中心
staticmethod()用于創(chuàng)建靜態(tài)函數(shù)。靜態(tài)方法不綁定到對象,它綁定到類。這意味著,如果對象沒有綁定到靜態(tài)方法,則靜態(tài)方法不能修改對象的狀態(tài)。

專注于為中小企業(yè)提供成都網(wǎng)站設(shè)計、成都網(wǎng)站制作服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)尚義免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了上千多家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
使用staticmethod()的語法。
**staticmethod (function)** #Where function indicates function name
為了在類中定義靜態(tài)方法,我們可以使用內(nèi)置的 decorator @staticmethod。當(dāng)函數(shù)用@staticmethod 修飾時,我們不傳遞類的實(shí)例。這意味著我們可以在類中編寫一個函數(shù),但是不能使用該類的實(shí)例。
使用@staticmethod 裝飾器的語法。
**@staticmethod
def func(args, ...)** #Where args indicates function parameters
staticmethod()參數(shù):
只接受一個參數(shù)。參數(shù)通常是需要轉(zhuǎn)換為靜態(tài)的函數(shù)。我們也可以使用效用函數(shù)作為參數(shù)。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 功能 | 作為靜態(tài)方法創(chuàng)建的函數(shù)的名稱 | 需要 |
staticmethod()返回值
它以靜態(tài)方法返回給定的函數(shù)
| 投入 | 返回值 | | 功能 | 給定函數(shù)的靜態(tài)方法 |
Python 中staticmethod()的示例
示例 1:使用staticmethod()創(chuàng)建一個靜態(tài)方法
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:繼承如何與靜態(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("20-04-2021")
dateFromDB = DatesWithSlashes("20/04/2021")
if(date.getDate() == dateFromDB.getDate()):
print("Equal")
else:
print("Unequal")
輸出:
Equal示例 3:如何創(chuàng)建實(shí)用函數(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("/", "-")
date = Dates("12-03-2020")
dateFromDB = "12/03/2020"
dateWithDash = Dates.toDashDate(dateFromDB)
if(date.getDate() == dateWithDash):
print("Equal")
else:
print("Unequal")
輸出:
Equal 網(wǎng)頁標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python staticmethod()
當(dāng)前鏈接:http://www.dlmjj.cn/article/cdcdegj.html


咨詢
建站咨詢
