首页 > 编程语言 > 详细

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

时间:2016-03-04 01:50:35      阅读:151      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!