python 静态方法和类方法
class TestClassMethod(object): METHOD = 'method hoho' def __init__(self): self.name = 'leon' def test1(self): print 'test1' print self @classmethod def test2(cls): print cls print 'test2' print TestClassMethod.METHOD print '----------------' @staticmethod def test3(): print TestClassMethod.METHOD print 'test3' if __name__ == '__main__': a = TestClassMethod() a.test1() a.test2() a.test3() TestClassMethod.test3()
test1为实例方法
test2为类方法,第一个参数为类本身
test3为静态方法,可以不接收参数
类方法和静态方法皆可以访问类的静态变量(类变量),但不能访问实例变量,test2、test3是不能访问self.name的,而test1则可以
程序运行结果:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步