Function, method, static method and class method, Oh my!

Was working on a piece of Python software. For the first time I got to use Python’s @staticmethod. It all made sense. So this post will be about that.

Some quick notes:

Function: A function is a block of organized, reusable code that is used to perform a single, related action.

Method: It’s a function which is a member of a class.

def somethinger(arg1, arg2, ...): 
    print("Hello World!") 
    ....

Class Method: A class method receives the class as implicit first argument, just like an instance method receives the instance.

In Python you can specify class methods as the following:

class C(object):
    @classmethod 
    def f(cls, arg1, arg2, ...):
        ...

Please note how cls is called in as an argument. This could have been self. Which is usually constructed within a __init__ method.

Static Method: Neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class.

class C(object):
    @staticmethod
    def f(arg1, arg2, ...):
        ...

So why use it? I had used this for two reasons:

  1. It made sense keeping the function within the class: The software is couple thousand lines. You really don’t want to be looking for stuff for long.
  2. It didn’t use the class (self, cls) so why use it at all.

One must remember: Static method objects provide a way of defeating the transformation of function objects to method objects . A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. Static method objects are not themselves callable, although the objects they wrap usually are.

I hope this makes sense!

Have fun!