The function and difference of the flowing python-@staticmethod and @classmethod

Source: Internet
Author: User

In general, to use a method of a class, you need to instantiate an object before calling the method.

Instead of using @staticmethod or @classmethod, you can call it without instantiating it, directly from the class name. Method Name ().

This facilitates organizing the code, putting some functions that should belong to a class into that class, while facilitating the cleanliness of the namespace.

Since both @staticmethod and @classmethod can be called directly from the class name. Method Name (), what's the difference between them?

In terms of their use,

    • @staticmethod does not need to represent the self of its own object and the CLS parameters of its own class, just as with a function.
    • @classmethod also does not require the self parameter, but the first parameter needs to be a CLS parameter that represents its own class.

If you want to invoke some of the property methods of this class in @staticmethod, you can only direct the class name. The name of the property or class. Method name.

and @classmethod, because it holds the CLS parameter, can invoke the class's properties, class methods, instantiate objects, and so on, avoiding hard coding.

The code below.

1 classA (object):2Bar = 13     deffoo (self):4         Print 'Foo'  5  6 @staticmethod7     defStatic_foo ():8         Print 'Static_foo'  9         PrintA.barTen   One @classmethod A     defClass_foo (CLS): -         Print 'Class_foo'   -         PrintCls.bar the cls (). Foo () -    - A.static_foo () -A.class_foo ()

Output
Static_foo
1
Class_foo
1
Foo

Transferred from: http://blog.csdn.net/handsomekang/article/details/9615239

The function and difference of the flowing python-@staticmethod and @classmethod

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.