When to use static methods

One rule-of-thumb: ask yourself “Does it make sense to call this method, even if no object has been constructed yet?” If so, it should definitely be static. So in a class Car you might have a method: …which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built … Read more

Meaning of @classmethod and @staticmethod for beginner?

Though classmethod and staticmethod are quite similar, there’s a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all. Example Explanation Let’s assume an example of a class, dealing with date information (this will be our boilerplate): This class obviously could be used to store … Read more

Meaning of @classmethod and @staticmethod for beginner?

Though classmethod and staticmethod are quite similar, there’s a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all. Example Explanation Let’s assume an example of a class, dealing with date information (this will be our boilerplate): This class obviously could be used to store … Read more

Static methods in Python?

Yep, using the staticmethod decorator Note that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3) This is entirely identical to the first example (using @staticmethod), just not using the nice … Read more