Last active
July 12, 2021 16:09
-
-
Save kirankotari/e6959e74316352bfd06afa4d5ab8bd52 to your computer and use it in GitHub Desktop.
Python Decorator dependent on Class Instance variables
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
def myDecorator(arg1, arg2, arg3=None): | |
def wrap(f): | |
def fun_wrap(self, *args, **kwargs): | |
# TODO: before calling function | |
print(f"before method call, {self.arg1}") | |
f(self, *args, **kwargs) | |
# TODO: after calling function | |
print(f"after method call, {self.arg1}") | |
return fun_wrap | |
return wrap | |
class myClass: | |
def __init__(self, arg1, arg2): | |
self.arg1 = arg1 | |
self.arg2 = arg2 | |
self.instance_decorator() | |
def instance_decorator(self): | |
@myDecorator(self.arg1, self.arg2) | |
def myInnerMethod(self, arg): | |
print(f"inner method inputs: {arg}") | |
@myDecorator(self.arg1, self.arg2) | |
def myInnerMethod_noArgs(self): | |
print(f"inner method without args") | |
self.method_with_args = lambda arg: myInnerMethod(self, arg) | |
self.method_with_no_args = lambda: myInnerMethod_noArgs(self) | |
if __name__ == "__main__": | |
o = myClass("arg1", "arg2") | |
o.method_with_no_args() | |
o.method_with_args("arg") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment