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則可以
程序運行結果: