Skip to content

Instantly share code, notes, and snippets.

@inklesspen
Created October 25, 2008 03:16
Show Gist options
  • Save inklesspen/19678 to your computer and use it in GitHub Desktop.
Save inklesspen/19678 to your computer and use it in GitHub Desktop.
class SwitchingMethod(object):
"""This decorator turns a method into a classmethod,
but only when it's being called from the class;
it still works perfectly from the instance."""
def __init__(self, f):
self.f = f
def __get__(self, obj, klass=None):
if obj is None:
return classmethod(self.f).__get__(obj, klass)
return self.f.__get__(obj, klass)
class Test(object):
@SwitchingMethod
def hello(self_or_cls, msg):
print "Hello! %s" % msg
Test.hello("I am being called on the class!")
Test().hello("I am being called on an instance!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment