class MethodTest():
var1 ="class var"
def__init__(self, var2 = "object var"):
self.var2 = var2
@staticmethodpost
defstaticFun():
print'static method'
@classmethodspa
defclassFun(cls):
print 'class method'blog
staticmethod和classmethod的相同點:it
1.均可以經過類或實例調用class
mt = MethodTest()變量
MethodTest.staticFun()object
mt.staticFun()static
MethodTest.classFun()word
mt.classFun()ssm
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