Python ProgrammingPython Programming

How to access the class of an instance method from a decorator?

class Decorator(object):
  def __init__(self, decoratee_enclosing_class):
    self.decoratee_enclosing_class = decoratee_enclosing_class

  def __call__(self, original_func):
    def new_function(*args, **kwargs):
      print('decorating function in ', self.decoratee_enclosing_class)
      original_func(*args, **kwargs)
    return new_function


class Bar(object):
  @Decorator('Bar')
  def foo(self):
    print('in foo')


class Baz(object):
  @Decorator('Baz')
  def foo(self):
    print('in foo')


print('before instantiating Bar()')
b = Bar()
print('calling b.foo()')
b.foo()
Output
before instantiating Bar()
calling b.foo()
decorating function in  Bar
in foo