Last active
January 30, 2020 08:21
-
-
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.
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
# 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