Home  >  Article  >  Backend Development  >  python function - classmethod()

python function - classmethod()

高洛峰
高洛峰Original
2016-10-17 15:31:011333browse

classmethod(function)

Chinese description:

classmethod is used to specify a class method as a class method. The method of the class specified without this parameter is an instance method. The usage method is as follows:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

Class method You can either make a direct class call (C.f()) or an instance call (C().f()).

Version: New in python2.2, new features added in python2.4. Still available in python3.


English description:

Return a class method for function.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.


It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except 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, see staticmethod() in this section.


For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.


New in version 2.2.


Changed in version 2.4: Function decorator syntax added.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn