Python--@classmethod @staticmethod differences and use

Source: Internet
Author: User

Definitions in Python:

    1. Class MyClass:
    2. ...
    3. Modifier for @classmethod # Classmethod
    4. Def class_method (CLS, arg1, Arg2, ...):
    5. ...
    6. Modifier for @staticmethod # Staticmethod
    7. def static_method (arg1, Arg2, ...):
    8. ...

@classmethod: Class Methods

@staticmethod: Static methods

A class method can be called directly from a class, just as a call to a static method.

The difference: Class method, need to pass in the class, define the class method to pass a default parameter CLS. Static methods are not used.

Example:

123456789101112131415161718192021222324252627282930313233343536373839 #!/usr/bin/env python# -*- coding: utf-8 -*-# blog.ithomer.netclass Test(object):    x = 11    def __init__(self, _x):        self._x = _x        print("Test.__init__")     @classmethod    def class_method(cls):        print("class_method")     @staticmethod    def static_method():        print("static_method")     @classmethod    def getPt(cls):        cls.class_method()        cls.static_method() if "__main__" == __name__:    Test.class_method()         # class_method    Test.static_method()        # static_method    Test.getPt()                # class_method  static_method     t = Test(22)                # Test.__init__    t.class_method()            # class_method    t.static_method()           # static_method        print Test.x                # 11#     print Test._x        print t.x                   # 11    print t._x                  # 22     #     t.getPr()   # ‘Test‘ object has no attribute ‘getPr‘

Operation Result:

1234567891011121314 class_methodstatic_methodclass_methodstatic_methodTest.__init__class_methodstatic_method111122Traceback (most recent call last):  File "/home/homer/workspace/myPython/com/connmiliao.py", line 40, in <module>    t.getPr() AttributeError: ‘Test‘ object has no attribute ‘getPr‘</module>

Example: @property, @staticmethod, @classmethod

12345678910111213141516171819202122232425262728293031323334353637383940 #!/usr/bin/env python# -*- coding: utf-8 -*-# blog.ithomer.netclass MyClass(object):    def __init__(self):        print ‘__init__‘        self._name = ‘blog.ithomer.net‘    @staticmethod    def static_method():        print ‘This is a static method!‘    def test(self):        print ‘call test‘     @classmethod    def class_method(cls):        print ‘cls: ‘,cls        print ‘cls.name: ‘,cls.name        print ‘cls.static_method(): ‘,cls.static_method()        instance = cls()        print ‘instance.test(): ‘,instance.test()    @property    def name(self):        return self._name        @name.setter    def name(self, value):        self._name = valueif __name__ == ‘__main__‘:    MyClass.static_method()    MyClass.class_method()        mc = MyClass()    print mc.name    mc.name = ‘forum.ithomer.net‘    print mc.name

Operation Result:

This is a static method!
CLS: <class ' __main__.myclass ' = "" >
Cls.name:
Cls.static_method (): This is a static method!
None
__init__
Instance.test (): Call test
None
__init__
Blog.ithomer.net
Forum.ithomer.net

Python--@classmethod @staticmethod differences and use

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.