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

程序運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM