Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Last active January 30, 2020 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save internetimagery/52abc8eabe477aa7e0630cc126726483 to your computer and use it in GitHub Desktop.
Save internetimagery/52abc8eabe477aa7e0630cc126726483 to your computer and use it in GitHub Desktop.
Decorators broken down. Useful if needing to access the class or instance of a method from within a decorator, while it still needs to be a classmethod or staticmethod.
# Decoration broken down. Useful if needing to access the class or instance of a method from within a decorator, while it still needs to be a classmethod or staticmethod.
from functools import partial
class StaticMethod(object):
def __init__(self, function):
self._function = function
def __get__(self, instance, class_):
print("Static Method! Instance:", instance, "Class:", class_)
return self._function
class ClassMethod(StaticMethod):
def __get__(self, instance, class_):
print("Class Method! Instance:", instance, "Class:", class_)
return partial(self._function, class_)
class Method(StaticMethod):
def __get__(self, instance, class_):
print("Method! Instance:", instance, "Class:", class_)
return partial(self._function, instance)
if __name__ == "__main__":
class Test(object):
@StaticMethod
def test_staticmethod():
print("hello from static method")
@ClassMethod
def test_classmethod(cls):
print("hello from class method:", cls)
@Method
def test_method(self):
print("hello from method:", self)
test = Test()
test.test_staticmethod()
test.test_classmethod()
test.test_method()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment