Example methods, class methods, static methods, and common methods in Python

Source: Internet
Author: User
Tags instance method

To differentiate between them, write the following code:
1 classC:2 3     defSelf_method (Self, a):4         returna5 6 @classmethod7     defClass_method (CLS, a):8         returna9 Ten @staticmethod One     defStatic_method (a): A         returna -  -     defmethod (a): the         returna -  -if __name__ = = ' __main__ ': -c =C () +     Print(C.self_method ('Self Method')) -     Print(C.class_method ('class Method')) +     Print(C.static_method ('static Method')) A     #Print (C.method (' method ')) error running at     #Print (C.self_method (' self method ')) error running -     Print(C.class_method ('class Method')) -     Print(C.static_method ('static Method')) -     Print(C.method ('Method'))

So:

    1. When an instance method is defined, the first argument is an instance of the Class (self), which must be called through an instance when invoked. You can access instance properties and methods.
    2. Class methods use @classmethod decorations, the first parameter is a class (CLS), and can be called by an instance of the class or the class itself. You can access class properties and methods.
    3. Static methods use @staticmethod decorations, which can be invoked using an instance of the class or the class itself.
    4. The common method is to define a normal function in the class, which must be called by the class itself.

Example methods, class methods, static methods, and common methods in 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.