Python3 class methods, instance methods, and static methods

Source: Internet
Author: User

Today, we summarize the Python class method, the instance method and the static method.

Python defaults to instance methods, which means that only instance objects can invoke this method.

Does that mean that the class method can only be called by the class object itself, of course, not. A class method can be called either by a class object or by an instance object. You can understand that, assuming that I now define ' dog ', it has a class method ' chew Bones ', then for all dogs can not be called chew bones this method, in this case, I now create a ' Wong Choy ' instance, it can also go to chew bones, that is, can call this class method.

Static methods you can understand that a parameter can be arbitrarily set, and that both class and instance objects can invoke it.

#!usr/bin/env python#Coding:utf-8classA:defFuna (self):Print('instance Method') @classmethoddefFunb (CLS):Print('class Method') @staticmethoddeffunc ():Print('Static Methods')if __name__=='__main__':    #generate an Instance objectA =A () A.funa ()#Input: Instance method        #error: Typeerror:funa () Missing 1 required positional argument: ' Self '    #A.funa ()A.funb ()#input: Class methodA.funb ()#input: Class methodA.func ()#input: Static methodA.func ()#input: Static method

Summary: A method in a class belongs to an instance method when the adorner is not added, and can only be called by an instance object.

@classmethod class methods that can be called by Class objects and instance objects.

@staicmethod static methods can be called by Class objects and instance objects, and parameters can be set arbitrarily.

Python3 class methods, instance methods, and static methods

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.