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