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則可以

程序運行結果:

發佈了8 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章