Python @classmethod and @staticmethod differences

Source: Internet
Author: User

First of all, @staticmethod, this decorator is very well understood, is to let the method in the class into a static method, do not need to instantiate the object can be directly called. The "self" parameter cannot be used in this static method;

Look at @classmethod again. In fact, similar to the @staticmethod function, you can simply understand that the @staticmethod function adds a "CLS" parameter for this class of obj (in class inheritance, the CLS represents a subclass), and other objects in this class can be called by calling the CLS () object ( All are objects in Python.

If you do not understand the above two sentences, please look at the following code, you understand.

1 classTest (object):2Tag=13 4     defNormal_method (self):5         Print 'Normal Method'6 7 @classmethod8     defClass_method (CLS):9         Print 'class method, tag is%s'%CLS (). TagTen CLS (). Normal_method () One  A @staticmethod -     defStatic_method (): -         Print 'static method, tag is%s'%Test.tag the         #print ' Static method,tag is%s '% Test.class_method ()

Running Results >>>

>>> is 1>>> test.class_method ()class is 1normal Method

Python @classmethod and @staticmethod differences

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.