Python built-in functions (11) -- classmethod, pythonclassmethod

Source: Internet
Author: User

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.

 

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.