Returns the class function as a method of the class. The first parameter of a class method is the specified class, which, like a function in a class, is the specified class instance. The class method modifier is used in the following format:
Class C:
@classmethod
def f (CLS, arg1, Arg2, ...):
...
From the above format, the@classmethod is a function in front of a modifier, you can view the Language Reference manual. Functions that pass the class method modifier can be called directly through the class, such as c.f () , or by instance, such as C (). f ( ) , but this instance is ignored in this function. , and did not play any role. If a function of a class method modifier is inherited from a class, the derived class is passed as the first parameter to the function, that is, the cls equals the derived class.
The function defined by the class method modifier is not the same as a static function in C + + or JAVA , and if you want similar functionality, you need to use a different modifier staticmethod .
What is the purpose of classmethod design? is actually related to python Object-oriented programming, because python does not support multiple parameter overloading constructors, such as in C + + , A constructor can write multiple constructors, depending on the number of arguments. in order to solve this problem, Python uses the classmethod modifier so that the defined function can call these functions before the class object is instantiated, which is equivalent to multiple constructors , the code that solves multiple constructors is written outside of the class problem.
The difference from the modifier staticmethod is that the class method has a type parameter, and the static method does not. Static methods are mainly used to solve the problem of global function scope, and the class method is the problem of solving multiple constructors, so the application field is different.
Example:
#classmethod () class C: def __init__ (self, i): print (' __init__:%d '% i) @classmethod def f (CLS, name): print (name) return C (int (name)) a = C (1) b = c.f (' ten ') c = C (2). f (' + ') class D (C): pass D.F (' 20 ')
The output results are as follows:
__INIT__: 1
10
__INIT__: 10
__INIT__: 2
100
__INIT__: 100
20
__INIT__: 20
Python standard library: Built-in Functions classmethod (function)