📜  Python staticmethod()函数

📅  最后修改于: 2022-05-13 01:55:37.905000             🧑  作者: Mango

Python staticmethod()函数

Python staticmethod()函数用于将函数转换为静态函数。静态方法是属于类而不是类的实例的方法。静态方法不需要实例化。

示例 1: staticmethod() 应用的实现

Python3
class demoClass:
 
    def greet(msg):
        return msg
 
 
# convert the add to a static method
demoClass.greet = staticmethod(demoClass.greet)
 
# we can access the method without
# creating the instance of class
print(demoClass.greet("hai"))


Python3
class demoClass:
 
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
    def add(a, b):
        return a+b
 
    def diff(self):
        return self.a-self.b
 
 
# convert the add to a static method
demoClass.add = staticmethod(demoClass.add)
 
# we can access the method without creating
# the instance of class
print(demoClass.add(1, 2))
 
# if we want to use properties of a class
# then we need to create a object
Object = demoClass(1, 2)
print(Object.diff())


输出:

hai

在上面的代码中,创建了一个带有方法 greet() 的类,然后使用 staticmethod() 将其转换为静态方法,并且在不创建实例的情况下调用它,正如我们之前讨论过的,不需要创建调用静态方法的类。

示例 2: staticmethod() 应用的实现

Python3

class demoClass:
 
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
    def add(a, b):
        return a+b
 
    def diff(self):
        return self.a-self.b
 
 
# convert the add to a static method
demoClass.add = staticmethod(demoClass.add)
 
# we can access the method without creating
# the instance of class
print(demoClass.add(1, 2))
 
# if we want to use properties of a class
# then we need to create a object
Object = demoClass(1, 2)
print(Object.diff())

输出:

3
-1

如果我们不需要使用类属性,那么我们可以使用静态方法,在上面的代码中 add() 方法不使用任何类属性,因此使用 staticmethod() 将其设置为静态,并且需要调用 diff 方法通过创建一个实例,因为它使用类属性。