Python 中的 @staticmethod 装饰器是用于定义一个静态方法的修饰器。静态方法是一种特殊的方法,它不需要 self 参数,也不需要 class 参数,它只是一个普通的函数,只是被定义在类的内部。
1.示例
下面是一个使用 @staticmethod 的例子:
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
def instance_method(self):
print(f"Instance method, x={self.x}, y={self.y}")
@staticmethod
def static_method(a, b):
print(f"Static method, a={a}, b={b}")
obj = MyClass(10, 20)
obj.instance_method() # Output: Instance method, x=10, y=20
MyClass.static_method(100, 200) # Output: Static method, a=100, b=200
在这个例子中:
instance_method 是一个普通的实例方法,它需要 self 参数来访问实例属性。