Differences between staticmethod and classmethod in Python
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 similarities between staticmethod and classmethod are as follows:
1. Both can be called by class or instance
Mt = MethodTest ()
MethodTest. staticFun ()
Mt. staticFun ()
MethodTest. classFun ()
Mt. classFun ()
2. You cannot access instance members.
@ Staticmethod
DefstaticFun ():
PrintVar2 // Wrong
@ Classmethod
DefclassFun (cls ):
Print var2// Wrong
Differences between staticmethod and classmethod:
1. staticmethod requires no parameters. classmethod requires class variables to be passed as parameters (not class instances)
DefclassFun (cls ):
Print 'class Method'// Pass cls as class variables
2. classmethod can be a member of the callback class, but not a member of the staticmethod class.
@ Staticmethod
DefstaticFun ():
PrintVar1 // Wrong
@ Classmethod
DefclassFun (cls ):
Print cls. var1// Right