python基础知识讲解——@classmethod和@staticmethod的作用
在类的成员函数中,可以添加@classmethod和@staticmethod修饰符,这两者有一定的差异,简单来说:
@classmethod 必须有参数cls,在继承的子类中传入的cls变量为子类
@staticmethod 子类与父类的该方法相同
看代码:
class ParentClass: @classmethod def clsfun(cls): print cls.__name__+‘:classmethod‘ @staticmethod def stcfun(): print ‘ParentClass:staticmethod‘ class SonClass(ParentClass): pass ‘‘‘@classmethod def clsfun(cls): print ‘SonClass:classmethod‘ @staticmethod def stcfun(): print ‘SonClass:staticmethod‘ ‘‘‘ ParentClass.clsfun() ParentClass.stcfun() p = ParentClass() p.clsfun() p.stcfun() SonClass.clsfun() SonClass.stcfun() s = SonClass() s.clsfun() s.stcfun()
python基础知识讲解——@classmethod和@staticmethod的作用
原文:http://www.cnblogs.com/pylinux/p/5240625.html