Below for you to share an article on the Python @classmethod usage in detail, with a good reference value, I hope to be helpful to everyone. Come and see it together.
In the construction of a class in Python object-oriented programming, sometimes the use of @classmethod is encountered.
There is always a sense that the usage of this particular description is high-level usage, which is generally not available at my levels.
But I was curious to check it out.
It is generally understood that the method using the @classmethod modifier is exclusive to the class and can be called by the class name. To be able to demonstrate its differences from the general approach, write a simple code like this:
Class DemoClass: @classmethod def classprint (self): the print ("class method") def Objprint (self): Print ("obj method") obj = DemoClass () obj.objprint () Obj.classprint () Democlass.classprint () Democlass.objprint ()
The results of the execution of the program are as follows:
Grey@desktop-3t80npq:/mnt/e/01_workspace/02_programme_language/03_python/03_oop/2017/08$python Classmethod.pyobj methodclass methodclass Methodtraceback (mostrecent): File "classmethod.py", line in<m Odule> democlass.objprint () Typeerror:unboundmethod objprint () must BES called with DemoClass instance as first arg Ument (gotnothing instead) grey@desktop-3t80npq:/mnt/e/01_workspace/02_programme_language/03_python/03_oop/2017/ 08$exitexit E:\01_workspace\02_programme_language\03_python\03_oop\2017\08>pythonclassmethod.pyobj Methodclass methodclass Methodtraceback (mostrecent): File "classmethod.py", line, in<module> Democlass.objprint () Typeerror:objprint () Missing 1 required positional argument: ' Self '
Above the program execution, I was in two operating systems in the two Python version of the environment. Whether it's Py2 or Py3, the design is pretty much the same. In general, this usage is still very subtle. Because there is not enough actual combat experience, for the time being said bad this thing has what better advantage.