Systematic learning of Python - class: static method and class method - [Reasons for using static methods and class methods]

Category Catalog: General Catalog of "Systematic Learning Python"


As we have already learned, class methods usually pass the current instance object in their first parameter to act as an implicit subject of the method call-this is the "object" in "object-oriented programming". Today, however, there are two ways to modify this model. Before explaining these two methods, we should introduce why this is relevant to us.

Sometimes, a program needs to deal with data associated with a class rather than an instance. For example, you want to record the number of instances created by a class, or maintain a list of all instances of a class currently in memory. This form of information and the corresponding processing is associated with the class, not its instances. That is, this information is usually stored on the class itself and can be processed without requiring any instances.

For such tasks, a simple function written outside the class will often suffice. Because they can access class properties through the class name, they can access class data without going through an instance. However, to better tie such code to a class, and allow such procedures to be customized as usual with inheritance, it would be better to write such functions within the class itself. In order to do this, we need a method in the class that not only does not pass but also does not expect an selfinstance parameter.

Python supports such goals through the concept of static methods. Static methods are simple functions with no parameters that are nested within a class selfand are designed to operate on class properties rather than instance properties. Static methods do not accept an automatic selfparameter, whether called from a class or an instance. They typically log information across all instances rather than providing behavior for instances.

Although less commonly used, Python also supports the concept of class methods. Class methods are methods of a class in which the first parameter passed to them is a class object rather than an instance object, whether they are called through an instance or a class. This method can also access class data (as we often say) by passing their class parameters self, even when called through an instance. Regular methods (instance methods) need to accept an additional subject instance when called, but static methods and class methods do not.

References:
[1] Mark Lutz. Python Learning Manual[M]. Machinery Industry Press, 2018.

Guess you like

Origin blog.csdn.net/hy592070616/article/details/135433286