Created
October 25, 2008 03:16
-
-
Save inklesspen/19678 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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