Python @staticmethod and @classmethod
@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) @staticmethod def doSomething(x, y): return x + y print(Pizza.get_size) # <unbound method Pizza.get_size> (py2) # <function Pizza.get_size at 0x10efa1488> (py3) print(Pizza(10).get_size) # <bound method Pizza.get_size of <__main__.Pizza object # # at 0x1015ce150>> print(Pizza(10).get_size()) # 10 print(Pizza(10).whatever()) # 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): self.data = data # alternative constructor # init from a file @classmethod 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