19. Python staticmethod()

发布时间:2023-12-08

Python staticmethod()

更新:2022-07-24 11:11 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