Python staticmethod() 函数是一个内置函数,用于将给定的方法转换为静态方法。转换方法后,它不会绑定到类的实例,而是绑定到类本身。
与其他面向对象的编程语言一样,Python 也有静态方法的概念。可以直接调用这种类型的方法,而无需创建类的实例。
语法
以下是 Python staticmethod() 函数的语法 -
staticmethod(nameOfMethod)
参数
Python staticmethod() 函数接受单个参数 -
- nameOfMethod − 此参数表示我们想要转换为 static 的方法。
返回值
Python staticmethod() 函数返回一个静态方法。
staticmethod() 函数示例
练习以下示例来理解 Python 中 staticmethod() 函数的使用:
示例:使用 staticmethod() 方法
以下示例显示了 Python staticmethod() 函数的用法。在这里,我们正在创建一个执行两个数字相加的方法。然后,我们将此方法与类名一起作为参数值传递给 staticmethod(),以将其转换为静态方法。
class Mathematics:
def addition(valOne, valTwo):
return valOne + valTwo
Mathematics.addition = staticmethod(Mathematics.addition)
output = Mathematics.addition(51, 99)
print("The result of adding both numbers:", output)
当我们运行上述程序时,它会产生以下结果——
The result of adding both numbers: 150
示例:使用 @staticmethod 装饰器定义静态方法
为了定义静态方法,Python 提供了另一种方法,即使用 @staticmethod 装饰器。下面是创建名为 “subtraction” 的静态方法的示例。
class Mathematics:
@staticmethod
def subtraction(valOne, valTwo):
return valOne - valTwo
output = Mathematics.subtraction(99, 55)
print("The result of subtracting both numbers:", output)
以下是上述代码的输出 -
The result of subtracting both numbers: 44
示例:将 staticmethod() 与实用函数一起使用
在 Python 中,staticmethod() 的用例之一是 Utility Functions,这是一种实现可以经常重用的常见任务的方法。下面的代码演示了如何将 staticmethod() 与实用程序函数一起使用。
class Checker:
@staticmethod
def checking(value):
return isinstance(value, int)
print("Is the given number is integer:")
print(Checker.checking(142))
上述代码的输出如下 -
Is the given number is integer:
True
True