Python @staticmethod and @classmethod

@Static Method

@staticmethod it is a “normal” function inside a class. When this method is called, we don’t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can’t access the instance of that class (this is useful when your method does not use the instance).

A typical scenario involves a function that logically belongs to a class and we don’t want to have it floating around in the file, but at the same time it doesn’t really need any instance of the class to work.

A (probably not very good) example:

class Pizza(object):
    def __init__(self, size):
        self.size = size

    def get_size(self):
        return self.size

    def whatever(self):
        return self.doSomething(10, 20)

    def doSomething(x, y):
        return x + y

# <unbound method Pizza.get_size> (py2)
# <function Pizza.get_size at 0x10efa1488> (py3)

# <bound method Pizza.get_size of <__main__.Pizza object #
# at 0x1015ce150>>

# 10

# 30


@classmethod is a decorator for a method that must have a reference to a class object as its first parameter. Honestly, it looks like nobody has a damn clue what they’re really good for in real life, besides overloading constructors; since Python doesn’t have overloading, if we want multiple constructors that’s a way to do it.

class myClass(object):

    # default constructor
    # init from whatever built-in type
    def __init__(self, data=None): = data

    # alternative constructor
    # init from a file
    def init_file(cls, file_name):
        data = open(file_name).readline()
        return cls(data)

print myClass([1,2,3]).data
print myClass.init_file('/etc/hosts').data