title: Using decorator from base class both in base class and derived class
body: <p>I have some python objects with some methods in which i would like to do some check at the beggining, depending of this check, the method's code would run, or an execption would be raised. Instead of replicating the "check" code at the beginning of every method I though of doing a decorator, I also want the decorator to be embedded inside the class itself, since it is closely related to it. So basically:</p>
  
  <p>instead of this</p>
  
  <pre><code>class A(object):
  
      def a_method(self):
          if self.check_var is True:
              (some_code)
          else:
              raise Exception
  </code></pre>
  
  <p>I would like to have this</p>
  
  <pre><code>class A(object):
  
      def decorator(function):
          def function_wrapper(self, *args, **kwargs):
              if self.check_var is True:
                  return function(self, *args, **kwargs)
              else:
                  raise Exception
          return function_wrapper
  
      @decorator
      def a_method(self):
          (some_code)
  </code></pre>
  
  <p>My first question is, am I going about this right? or is there a better way. I have many methods of the A class that need to have this check, so that is why I don't want to replicate the code unnecessarily.</p>
  
  <p>My second question is, if I go about this the way I described, I run into a problem when I want to derive a class from class A and performe the same decorator checks. Again I don't want to replicate the code, so I want to reuse the decorator in the base class A to performe checks in the derived class. I read about turning the decorator into a <code>@classmethod</code> however when I do this I am able to use the decorator in the derived class but not in the base class anymore!</p>
  
  <p>So basically I would like something like this:</p>
  
  <pre><code>class A(object):
  
      @classmethod #maybe
      def decorator(function):
          def function_wrapper(self, *args, **kwargs):
              if self.check_var is True:
                  return function(self, *args, **kwargs)
              else:
                  raise Exception
          return function_wrapper
  
      @decorator
      def a_method(self):
          (some_code)
  
  class B(A):
  
      @decorator
      def b_method(self):
          (some_code)
  </code></pre>
  
  <p>Does anybody know of any clean way to do this?</p>