2022年 11月 3日

Python静态方法

Python静态方法

什么是静态方法?静态方法是干什么的?在Python里面静态方法和我们平时写的函数def是一样的。唯一不同之处就是它可以存在于类中,不同实例化类也可以调用。话不多说,通过例题看一下。
例题思路:
在类中编写静态方法和类的普通方法

class Static:
    @staticmethod
    def test_static():
        print('I am staticmethod')
        
    def test_def(self):
        print('I am not staticmethod')

'调用静态方法'
Static.test_static()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在这里插入图片描述
可以看出静态方法可以直接被调用,且不用加任何参数、self也不要。静态方法存在的意义其实就是让函数归类,紧耦合。