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 '
The same points as Staticmethod and Classmethod:
1. Can be called from a class or instance
MT = Methodtest ()
Methodtest.staticfun ()
Mt.staticfun ()
Methodtest.classfun ()
Mt.classfun ()
2. Cannot access instance members
@staticmethod
Defstaticfun ( ):
print var2 c19> //wrong
@classmethod
Defclassfun (CLS):
print var2 //wrong
The difference between Staticmethod and Classmethod:
1.staticmethod without parameters, Classmethod requires class variables to be passed as arguments (not an instance of the class)
Defclassfun (CLS):
print ' class method '//cls passed as a class variable
2.classmethod can access class members, Staticmethod can not
@staticmethod
Defstaticfun ( ):
print var1 c30> //wrong
@classmethod
Defclassfun (CLS):
print cls.var1 //right
Similarities and differences of Staticmethod and Classmethod in Python