python基础知识讲解——@classmethod和@staticmethod的作用

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()

  

 

posted on 2016-03-04 00:01  pylinux  阅读(134)  评论(0)    收藏  举报

导航