Python built-in functions (11) -- classmethod, pythonclassmethod
English document:
classmethod(Function)
Return a class methodFunction.
A class method has es the class as implicit first argument, just like an instance method has es the instance. To declare a class method, use this idiom:
class C: @classmethod def f(cls, arg1, arg2, ...): ...
The@classmethodForm is a function decorator-see the description of function definitions in Function definitions for details.
It can be called either on the class (suchC.f()) Or on an instance (suchC().f()). The instance is ignored before t for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Class methods are different than C ++ or Java static methods. If you want those, seestaticmethod()In this section.
Note:
1.Classmethod is a modifier function that identifies a method as a class method.
2. The first parameter of the class method is the class object parameter. When the method is called, the class object is automatically passed in. The parameter name convention is cls.
3. if a method is labeled as a class method, the method can be called by class objects (such as C. f () can also be called by class instance objects (such as C (). f ())
>>> Class C: @ classmethod def f (cls, arg1): print (cls) print (arg1) >>> C. f ('class object call class method') <class '_ main __. c'> class object call class method >>> C = c () >>> C. f ('class instance object call class method') <class '_ main __. C '> class instance object call class Method
4. After the class is inherited, The subclass can also call the class method of the parent class, but the first parameter is passed into the class Object of the subclass.
>>> Class D (C): pass >>> D. f ("The subclass class Object calls the class method of the parent class") <class '_ main __. D '> the Class Object of the subclass calls the class method of the parent class.