标签:
在python中,静态方法和类方法都是可以通过类对象和类对象实例访问。但是区别是:
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
Python中的staticmethod和classmethod
标签:
原文地址:http://www.cnblogs.com/Bbrook/p/4354655.html