The roles and differences of Python @staticmethod and @classmethod __python

Source: Internet
Author: User

Reference: http://blog.csdn.net/handsomekang/article/details/9615239


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


As we have defined a

Class A ():

Def __init__ ():

Print "A"

Def show ():

Print "Test"

A = ClassA ()

A.show ()


Using @staticmethod or @classmethod, you can do so without instantiating the direct class name. Method name () to invoke.


After modification:

Class A ():

Def __init__ ():

Print "A"

@staticmthod

Def show ():

Print "Test"

A.show ()



Since both @staticmethod and @classmethod can be directly class names. The method name () is invoked, so what's the difference between them? In terms of their use,
@staticmethod do not need to represent the CLS parameters of self and its own class for the object itself, as with functions. The self parameter is not required for @classmethod, but the first argument needs to be the CLS parameter representing its own class.

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

@classmethod because it holds CLS parameters, you can invoke the properties of the class, the method of the class, instantiate the object, and so on, to avoid hard coding.

The code below.

[Python]View plain Copy class A (object): bar = 1 def foo (self): print ' foo ' @staticmethod def           Static_foo (): print ' Static_foo ' Print A.bar @classmethod def class_foo (CLS): print ' Class_foo ' Print Cls.bar cls (). Foo () A.static_foo () A.class_foo () output
Static_foo
1
Class_foo
1
Foo

This is good for organizing code, putting some functions that should belong to a class into that class, while facilitating the cleanliness of namespaces.

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.