码迷,mamicode.com
首页 > 编程语言 > 详细

python中的静态方法和类方法的区别【转】

时间:2015-07-08 12:24:32      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
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则可以

程序运行结果:

技术分享

python中的静态方法和类方法的区别【转】

标签:

原文地址:http://www.cnblogs.com/Blaxon/p/4629537.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!