静态方法 staticmethod
两种方式使用staticmethod
-
staticmethod(function)
-
@staticmethod
def func(args, ...)
使用静态方法的情况:
- 需要在类中定义函数,并且不需要涉及类自身的属性,而只需要输入参数时。
- 不希望在所定义类的子类中,改写该函数。
静态方法的代码示例
"""
自定义Myclass类
"""
class Myclass:
def __init__(self):
self.x = 0
def add(self, y):
return self.x + y
@staticmethod # 在类中定义了静态函数,并且没有使用self参数,不需要使用类内部属性
def multiply(a, b):
return a * b
def subtract(a, b):
return a - b
# 第一种方法:创建类的实例
my_class = Myclass() # 创建类的实例
summation = my_class.add(10) # 调用静态函数
# 第二种方法:不需要创建类,直接调用
product1 = Myclass.multiply(10, 20) # 不需要类的实例
# 第三种方法:使用staticmethod()将类中的方法转化为静态函数
Myclass.subtract = staticmethod(Myclass.subtract) # 使用staticmethod()转化类中的函数
product2 = Myclass.subtract(10, 20) # 转化后,直接调用静态函数
print('The output of the class function is {}'.format(summation))
print('The output of the static class function is {}'.format(product1))
print('The output of the static class function using staticmethod() is {}'.format(product2))
OUTPUT:
The output of the class function is 10
The output of the static class function is 200
The output of the static class function using is -10