python @classmethod 和 @staticmethod

python中有三种调用method的方法:普通method,staticmethod和classmethod

正常的类对象,self, 而classmethod要传入类, staticmethod不用传。

staticmethod不能访问类成员变量。

 

class MethodTest():
    var1 = "class var"
   
    def __init__(self, var2 = "object var"):
        self.var2 = var2
   
    @staticmethod

    def staticFun():
        print 'static method' 
   
    @classmethod

    def classFun(cls):
        print 'class method'

 

staticmethod和classmethod的相同点:

1.都可以通过类或实例调用

mt = MethodTest()

MethodTest.staticFun()

mt.staticFun()

MethodTest.classFun()

mt.classFun()

2.都无法访问实例成员

    @staticmethod

    def staticFun():
        print var2  //wrong 
    @classmethod

    def classFun(cls):
        print var2  //wrong

 

staticmethod和classmethod的区别:

1.staticmethod无需参数,classmethod需要类变量作为参数传递(不是类的实例)

    def classFun(cls):
        print 'class method'  //cls作为类变量传递

2.classmethod可以访问类成员,staticmethod则不可以

    @staticmethod

    def staticFun():
        print var1  //wrong 
    @classmethod

    def classFun(cls):
        print cls.var1  //right

posted @ 2014-07-14 18:28  zizi_come  阅读(170)  评论(0编辑  收藏  举报