Class methods (@classmethod) and Static methods (@staticmethod) in the "developer Notes" python

Source: Internet
Author: User
Tags instance method

In high-level languages such as Java and C #, we define static and static variables using static, so how do you define static and static variables in Python?

Python provides @classmethod and @staticmethod to define static methods, which are not quite clear at the moment of contact, and stack overflow provides a more understandable explanation, stack overflow answers.

But after reading or not quite understand, so I wrote an example:

Class Stclass ():    d=1    #对象方法    def imethod (self):        print (self)        print ("instance method")    #类方法    @classmethod    def cmethod (CLS):        print (CLS)        print ("class method")    #静态方法    @staticmethod    def smethod ():        print ("static method") SC = Stclass () Sc.imethod () Sc.cmethod () Sc.smethod ()

The results of the operation are as follows:

Then we can explain:

1, the instance method, which belongs to the object, the first parameter of the method is the current instance, owns the current class and all the attributes of the instance.

2, the class method, the instance belongs to the class, the first parameter of the method is the current class, you can do some processing of the class, if a static method and the class is concerned but not related to the instance, then use this method.

3, the static method, the instance belongs to the class, but the method has no parameters, that is, the method can not do the class processing, equivalent to the global method.

Class methods (@classmethod) and Static methods (@staticmethod) in the "developer Notes" 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.