In object-oriented programming, class methods and static methods are the two terms commonly used.
Logically, a class method can be invoked only by a class name, and a static method may be invoked by a class name or an object name.
In C + +, static methods are logically equivalent to class methods, with only one concept and no confusion.
In Python, the method is divided into three kinds of instance methods, class methods and static methods. The code is as follows:
Class Test (object):
def instancefun (self):
Print ("Instancefun")
Print (self)
@classmethod
def classfun (CLS):
Print ("Classfun")
Print (CLS)
@staticmethod
Def staticfun ():
Print ("Staticfun");
t = Test ();
T.instancefun (); # output Instancefun, Print object memory address ' <__main__. Test object at 0x0293dcf0> "
Test.classfun (); # Output Classfun, print class position <class ' __main__. Test ' >
Test.staticfun (); # Output Staticfun
T.staticfun (); # Output Staticfun
T.classfun (); # Output Classfun, print class position <class ' __main__. Test ' >
Test.instancefun (); # error, Typeerror:unbound method Instancefun () must is called with Test instance as-a-argument
Test.instancefun (t); # output Instancefun, Print object memory address ' <__main__. Test object at 0x0293dcf0> "
T.classfun (Test); # error Classfun () takes exactly 1 argument (2 given)
As you can see in Python, the main difference between the two methods is the parameters. The argument implied by an instance method is class instance self, and the parameter implied by the class method is the class itself CLS.
Static methods have no implied parameters, mainly for class instances or direct calls to static methods.
So logically class methods should be called only by class, instance method instances, and static methods both. The main difference is the difference in parameter passing, where the instance method silently passes the self reference as a parameter, while the class method silently passes the CLS reference as an argument.
Python enables a certain amount of flexibility so that both class and static methods can be invoked by both instances and classes to: http://blog.csdn.net/a2806005024/article/details/30482731