Classmethod and Staticmethod in Python

Source: Internet
Author: User

First of all, this is a classic question.

Let's first make a comparison:

The first parameter of the Classmethod is the CLS, which is called to pass the class to the

This means that we can use the properties of the class in Classmethod instead of the properties of the instance of the class (explicit creation is available)

Staticmethod, there are no arguments at the time of invocation, that is, we do not pass in things (classes, instances of classes).

This means that we cannot get an instance of the class in Staticmethod (explicit creation is available)

And when we call the normal method of the class, we 're going to pass the self in.

This means that in this common method, we can only use the property method of the instance of the Class (self)

As for how to call it? See below:

 class   A (object): Bar  = 1 def   foo (self):  print
      " foo   '  
    @classmethod      def  Class_foo (CLS):          print'class_foo  '          print cls.bar  #  equals call to A.bar        cls (). Foo ()      #  equals call A (). Foo ()  a.static_foo ()  A.class_foo (   )

Output:

Static_foo, 1,foo

Class_foo,1,foo

Glance

Classmethod and Staticmethod in Python

Related Article

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.