There are 4 ways to do this in Python:
1) The global method in the module, which does not belong to any class, is called by the "module name. Method Name" form.
2) The instance method defined in the class, also becomes the binding method (Bound methods), the first parameter of this method (usually writing self, similar to Java and C + +), must be called the method's instance itself, when the method is called, Python will automatically pass that instance to the method.
3) A static method defined in a class, like a static method in Java, requires no instance as a parameter to the method, which can be called in the form of "class name. Method Name" (also called with the "instance. Method Name" form), and when defining a method, it needs to be decorated with the @staticmethod modifier.
4) There is also a method called a class method, also defined in the class, with the class name and instance can be called (that is, "class name. Method Name", "instance. Method Name"), the first parameter of the class method (usually the CLS), must be the class containing the method, when the method is defined, It needs to be decorated with the @classmethod modifier, and Python automatically passes the class as a parameter to the class method when the method is called.
Test code:
1 #Encoding:utf-82 classMyClass ():3Name="'4 def __init__(self,name):5Self.name=name6 7 deffoo (self,x):8 Print 'Calling bound Method foo () by instance "%s", x=%s.'%(self.name,x)9 Ten@staticmethod#static method Modifiers One deffoostatic (z): A Print 'calling static method Foostatic (), z=%s.'%Z - -@classmethod#class method Modifiers the deffoocls (cls,y): - Print 'Calling class Method Foocls () by class "%s", y=%s.'%(cls,y) - - if __name__=='__main__': + Print '-----------Start invoking the instance method below-------------' -Mc=myclass ('MC') +Mc.foo (5) A Print '-----------Start calling the class method below---------------' atMYCLASS.FOOCLS (10) -MC.FOOCLS (10) - Print 'The static method is called-----------below-------------' -Myclass.foostatic (15) -Mc.foostatic (15)
Output Result:
-----------start invoking the instance method below-------------Calling bound Method foo () by instance"MC", x=5..-----------start calling the class method below-------------callingclassMethod Foocls () byclass "__main__. MyClass", y=10.. CallingclassMethod Foocls () byclass "__main__. MyClass", y=10..The static method is called-----------below-------------calling static method Foostatic (), Z=15.. Calling static method Foostatic (), Z=15.
Python class features (3): Static Methods and Class methods