staticmethod() 用于创建一个静态函数。静态方法不绑定到对象,而是绑定到类。这意味着如果静态方法未绑定到对象,则无法修改对象的状 态。
使用 staticmethod() 的语法。
staticmethod (function) #Where function indicates function name
要在类中定义静态方法,我们可以使用内置装饰器 @staticmethod。当函数用 @staticmethod 装饰时,我们不传递类的实例。这意味着我们可以在类内部编写函数,但不能使用该类的实例。
使用 @staticmethod 装饰器的语法。
@staticmethod
def func(args, ...) #Where args indicates function parameters
只接受一个参数。该参数通常是需要转换为静态的函数。我们也可以使用实用函数作为参数。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 函数 | 创建为静态方法的函数的名称 | 必需 |
它将给定的函数作为静态方法返回
| 输入 | 返回值 |
|---|---|
| 函数 | 给定函数的静态方法 |
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
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
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