In Python, both static and class methods can be accessed through class objects and class object instances. But the difference is:
- @classmethod is a function modifier, which means that next is a class method, which is called an instance method for what we usually see. The first parameter of the class method is CLS, and the first argument of the instance method is self, which represents an instance of the class.
- A normal object method requires at least one self parameter, which represents the Class object instance
- Class methods have the class variable CLS incoming, so that some related processing can be done with the CLS. and with subclass inheritance, when the class method is called, the passed-in class variable CLS is a subclass, not a parent class. for a class method, it can be called through a class, like C.F (), a bit like a static method in C + +, or it can be called through an instance of the class, like C (). f (), here C (), written so that it is an instance of the class.
- Static method is not, it is basically the same as a global function, generally used very little
Classmethodtest (): Var1="class Var" def __init__(Self, var2 ="object var"): Self.var2=var2 @staticmethoddefStaticfun ():Print 'static Method'@classmethoddefClassfun (CLS):Print 'class Method'the same points as Staticmethod and Classmethod:1you can call Mt from a class or instance.=methodtest () Methodtest.staticfun () Mt.staticfun () Methodtest.classfun () Mt.classfun ()2. Cannot access instance members @staticmethoddefStaticfun ():PrintVAR2//wrong @classmethoddefClassfun (CLS):PrintVAR2//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'//The CLS is passed as a class variable2. Classmethod can access class members, and Staticmethod can not @staticmethoddefStaticfun ():PrintVAR1//wrong @classmethoddefClassfun (CLS):PrintCls.var1//right
Staticmethod and Classmethod in Python