Skip to content

Instantly share code, notes, and snippets.

@gennad
Created May 28, 2011 11:45
Show Gist options
  • Save gennad/996808 to your computer and use it in GitHub Desktop.
Save gennad/996808 to your computer and use it in GitHub Desktop.
Class method vs Static method
"""
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. Observe for instance how
dict.fromkeys(), a classmethod, returns an
instance of the subclass when called on a
subclass:
A staticmethod isn't useless - it's a way of putting a function into a class (because it logically belongs there), while indicating that it does not require access to the class.
"""
class A(object):
def foo(self,x):
print "executing foo(%s,%s)"%(self,x)
@classmethod
def class_foo(cls,x):
print "executing class_foo(%s,%s)"%(cls,x)
@staticmethod
def static_foo(x):
print "executing static_foo(%s)"%x
a=A()
a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)
a.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)
A.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)
a.static_foo(1)
# executing static_foo(1)
print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>
print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>
print(a.static_foo)
# <function static_foo at 0xb7d479cc>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment