Home > Back-end >  Keep decorator on override method
Keep decorator on override method

Time:09-29

I've got a parent class with a method used many times and override all the time. This method has a decorator. I would like to reuse the decorator each time I override the methode without using super() or rewrite de decorator

def decorator(method):
   def wrapper(self, *args, **kwargs):
      print("how are you ?")
      method(self, *args, **kwargs)
   return wrapper

class A:
    @decorator
    def method_a(*args, **kwargs):
       pass

class B(A):
    def method_a(*args, **kwargs):
        print("Fine thanks !")

class_b = B()
class_b.method_a()

# How are you ?
# Fine thanks !

CodePudding user response:

I think the cleanest way would be to make an additional function, e.g. _method_a that contains the core of a function, and decorated method_a that only calls the other one. In the child classes you can reimplement _method_a, while leaving method_a from inheritance, thus still decorated.

class A:
    @decorator
    def method_a(self, *args, **kwargs):
        return self._method_a(args, kwargs)

    def _method_a(*args, **kwargs):
        pass

class B(A):
    def _method_a(*args, **kwargs):
        print("Fine thanks !")
  • Related