Python_类方法&静态方法
类方法
>>> class P: ... @classmethod#类方法 ... def print_str(cls,content):#类方法 ... print(content) ... >>> P.print_str("hello")#类不用实例化,可直接调用 hello >>> p=P()#实例化的调用 >>> p.print_str("hi")#实例化的调用 Hi
静态方法
>>> class P: ... @staticmethod#静态方法的标记 ... def print_str(content):#静态方法没有cls ... print(content) ... >>> P.print_str("hi") Hi >>> class P: ... @staticmethod ... def print_str(content): ... print(content) ... >>> P.print_str("hi")#类的直接调用 hi >>> p=P() >>> p.print_str("hello")#对象的直接调用 Hello
注意:
静态方法和类方法只能使用类变量
静态方法不需要实例