Python standard library: built-in functions classmethod (function), pythonclassmethod
Class functions are returned as a class method. The first parameter of a class method is to specify a class. Like a function in a class, the first parameter is to specify a class instance. The class method modifier is in the following format:
Class C:
@ Classmethod
Def f (cls, arg1, arg2 ,...):
...
From the above format, @ classmethod is a modifier before the function. You can view the language reference manual. Functions with class method modifiers can be called directly through classes, such as C. f () method, or you can call it through an instance, such as C (). f () method, but this instance is ignored in this function. If the class method modifier function inherits the class, the derived class is passed to this function as the first parameter, that is, cls is equal to the derived class.
The class method modifier defines different functions than the static functions in C ++ or JAVA. To use similar functions, use another modifier staticmethod.
What is the purpose of classmethod design? In fact, it is related to Python object-oriented programming, because Python does not support multiple parameter overload constructors. For example, in C ++, constructors can vary according to the number of parameters, you can write multiple constructors. To solve this problem, Python uses the classmethod modifier so that the defined functions can call these functions before class Object Instantiation, which is equivalent to multiple constructors, solve the Problem of writing code of multiple constructors outside the class.
The difference from the modifier staticmethod is that the class method has a type parameter, but the static method does not. Static methods are mainly used to solve the problem of the scope of global functions, while class methods are used to solve the problem of 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('10')c = C(2).f('100') class D(C): pass D.f('20')
The output result is as follows:
_ Init __: 1
10
_ Init __: 10
_ Init __: 2
100
_ Init __: 100
20
_ Init __: 20