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