Skip to content

Instantly share code, notes, and snippets.

@kirankotari
Last active July 12, 2021 16:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirankotari/e6959e74316352bfd06afa4d5ab8bd52 to your computer and use it in GitHub Desktop.
Save kirankotari/e6959e74316352bfd06afa4d5ab8bd52 to your computer and use it in GitHub Desktop.
Python Decorator dependent on Class Instance variables
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