Python functions-classmethod ()

Source: Internet
Author: User
Python functions-classmethod () classmethod (function)

Chinese description:

Classmethod is used to specify a class method as a class method. if the class method not specified by this parameter is an instance method, the usage is as follows:

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

The class method can be called directly (C. f () or an instance call (C (). f ()).

Version: Added in python2.2 and added new features in python2.4. Python3 is still available.


English description:

Return a class method for function.

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 @ 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 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, 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.


Code example:

>>> class C:...     @classmethod...     def f(self):...             print "This is a class method"...>>> C.f()This is a class method>>> c = C()>>> c.f()This is a class method>>> class D:...     def f(self):...             print " This is not a class method "...>>> D.f()Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)>>> d = D()>>> d.f()This is not a class method
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.