Application of three kinds of functions in class
#!/usr/bin/env python#-*-Coding:utf-8-*- class tclassstatic(object): def __init__(self, data):Self.data = Data def printself(*arg): # for item in ARG: # Print Item.dataPrint"Printself:", ARG)@staticmethod def smethod(*arg):Print"stattic:", ARG)@classmethod def cmethod(*arg):Print"class:", ARG) def main():obj = tclassstatic (Ten) obj.printself () Obj.smethod () Obj.cmethod ()if__name__ = ="__main__": Main ()
It is clear from the invocation of three functions that the default parameters of the various functions, the output is as follows:
(‘printself: ‘, (<__main__.TClassStatic object at 0x6ffffe22910>,))(‘stattic: ‘, ())(‘class: ‘, (<class ‘__main__.TClassStatic‘>,))
1, the normal function, the default incoming parameter self, equivalent to the this pointer in C + +. The data for the first parameter is the data (10) of the object that can be output by releasing the annotations in Printself. The definition of such a function def printself(self, *args, **kwargs)
is usually, its characteristic is that the first argument is self, when called, only the Args,kwargs value is passed, the instance object. Method
2, @staticmethod modified function, equivalent to a class in C + + static functions, can be applied as a global function, the default does not pass in parameters, call Method: Instance object or Class object. Methods
3, @classmethod modified function, the first parameter CLS is the class name by default, call Method: Instance object or Class object. method
Application examples of @classmethod and @staticmethod
#!/usr/bin/env python#-*-Coding:utf-8-*- class tclassstatic(object):Obj_num =0 def __init__(self, data):Self.data = Data Tclassstatic.obj_num + =1 def printself(self):Print"Self.data:", Self.data)@staticmethod def smethod():Print"The number of obj is:", Tclassstatic.obj_num)@classmethod def cmethod(CLS):Print"Cmethod:", Cls.obj_num) Cls.smethod () def main():Obja = Tclassstatic (Ten) OBJB = Tclassstatic ( A) objb.printself () Obja.smethod () Objb.cmethod () print ("------------------------------") Tclassstatic.smethod () Tclassstatic.cmethod ()if__name__ = ="__main__": Main ()
The output results are as follows:
(' Self.data: ', A)(‘ the Number ofObj is: ‘,2) (' Cmethod: ',2)(‘ the Number ofObj is: ‘,2)------------------------------(‘ the Number ofObj is: ‘,2) (' Cmethod: ',2)(‘ the Number ofObj is: ‘,2)
The difference and application of Classmethod and Staticmethod in Python