title: Reusable validating class attributes
body: <p>I have a class which implements attributes through the <code>@property</code> decorator as follows</p>
  
  <pre><code>class num(object):
  
      def __init__(self, value):
          self.val = value
  
      @property
      def val(self):
          return self._val
  
      @val.setter
      def val(self, value):
          validation(self, (int, float), value, 0.0)
  </code></pre>
  
  <p>When the value of the attribute is to be set, it should get validated. </p>
  
  <pre><code>def validation(obj, types, value, default):
      """Checks if the input provided for the attribute is valid."""
      try:
          if not isinstance(value, types):
              obj._val = default
              raise TypeError
          if value &lt; 0:
              obj._val = default
              raise ValueError
          else:
              obj._val = float(value)
      except ValueError as e:
          print("Should be a positive number. Value set at ", default)
      except TypeError:
          print("Should be a number. Value set at ", default)
  </code></pre>
  
  <p>This code works for this particular case, where I have just one a priori known attribute <code>val</code>. I would like to make the function <code>validation</code> more general, to be able to reuse for other attributes (for example an arbitrary index). I can see that my problem resides in the <code>obj._val</code>, where I'm breaking encapsulation.</p>
  
  <p>I guess that one possible solution is through the use of a method decorator chained to the setter of the attribute or maybe passing an extra argument to <code>validation</code> to be aware of which attribute has to validate. Or perhaps is by using a completely different approach.</p>
  
  <p>Thanks in advance!</p>