首页 > 代码库 > Python中的staticmethod和classmethod 的异同

Python中的staticmethod和classmethod 的异同

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

    defstaticFun():
        print‘static method‘ 
   
   @classmethod

    defclassFun(cls):
       print ‘class method‘

 

staticmethod和classmethod的相同点:

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

mt = MethodTest()

MethodTest.staticFun()

mt.staticFun()

MethodTest.classFun()

mt.classFun()

2.都无法访问实例成员

   @staticmethod

    defstaticFun():
        print var2  //wrong 
   @classmethod

    defclassFun(cls):
       print var2  //wrong

 

staticmethod和classmethod的区别:

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

    defclassFun(cls):
       print ‘class method‘  //cls作为类变量传递

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

   @staticmethod

    defstaticFun():
        print var1  //wrong 
   @classmethod

    defclassFun(cls):
       print cls.var1  //right

Python中的staticmethod和classmethod 的异同