@staticmethod
是 Python 中的一个装饰器,用于将类的方法定义为静态方法。静态方法不接收隐式的 self
参数,因此不能访问类的实例属性或其他方法。它使得方法可以不依赖于类或实例的状态,从而提高代码的模块化和重用性。静态方法通常用于实现与类相关的功能,但不需要类的状态信息。
可以用在工具类里面
class Utils:
@staticmethod # staticmethod 装饰器同样是用于类中的方法,这表示这个方法将会是一个静态方法
def say_hello(): # 但同样意味着它没有 self 参数
print('hello')
# 该方法可以直接被调用无需实例化
Utils.say_hello() # hello
# 实例化调用也是同样的效果
# 有点多此一举
utils = Utils()
utils.say_hello() # hello
class Utils:
@staticmethod
def say_hello():
print('hello')
Utils.say_hello() # hello
utils = Utils()
utils.say_hello() # hello
让函数归类,紧耦合