self parameter to work properly, however, there are two notable exceptions to this rule that are worth learning about. They are classmethods and staticmethods.
staticmethod
A method is said to be “static” when it doesn’t use the class properties at all. In other words, “self” is unused within the method body. However, you can’t then remove the parameter self from the definition because it has to be there for methods to work. Unless, that is, you use the decorator staticmethod on the method. If that is applied you can remove the self parameter and still have other non-self parameters. Static methods like this can still be called using self within other methods, but they can also be called via the class and instances of the class. Why would you ever want to do this though? It crops up surprisingly often, but generally you may want to group utility functions together to make them easier to use.
For example, consider the Coordinate class from Part 4. A static method is generally a method or function that is strongly associated with the class, even if it doesn’t use the class properties.
Coordinate we might want to create a utility function to get possible values of x, y and z. Let’s fix the minimum and maximum values of the three dimensions as constants at the beginning of the file. Now we can call them in the class. Our staticmethod would look something like this.
self. If you still aren’t convinced by this tool’s efficacy don’t worry. Once you’ve created your own classes and developed your own software using them, you will come across situations like this and this is a tool for those times.
classmethod
Class methods are just as easy to create and apply as static methods, but they have a very different purpose. Class methods are instance creation methods. This is easier to explain with an example. To do so, let’s consider the ThreeDimensionalSpace class from Part 4.
Coordinate for every point, but all we need to know to do this is really the minimum and maximum values for x, y, and z. Since x, y, and z must be integers we can work out every possible coordinate from just 6 numbers: min and max of x, y, and z.
However, the class ThreeDimensionalSpace needs us to create the set of all these coordinates every time before we can instantiate it. What if we built it in?
classmethod. This is a method that can be called from the class itself, or an instance of a class like staticmethod, and its selling point is that it creates a new instance of the class. The first parameter for a method decorated with classmethod must always be cls, which is the constructor of the class. In practice this lets you add class-creation shortcuts to your work. It can even be used as the only way to instantiate the class, which can be useful when you don’t want users to construct the class themselves in the “normal” way or perhaps there is a private way of instantiating the class that you don’t want users to see.