Python: class method vs static method

class A:
def object_m(self,x):
print "executing object_m(%s,%s)"%(self,x)

def class_m(cls,x):
print "executing class_m(%s,%s)"%(cls,x)

def static_m(x):
print "executing static_m(%s)"%x

According to stackoverflow:

A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.

A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved.

No comments:

Post a Comment