title: How to create attribute only for objects that satisfy a condition in Python?
body: <p>I would like to know how to define attributes only for objects that satisfy a condition raising an error if an object without the condition is asked for that attribute.</p>
  <pre><code>class Polynomial:
      def __init__(self, number_of_variables:int):
          self.number_of_variables = number_of_variables
          if self.is_univariate():
              self.nroots = compute_number_of_roots(self) # This function returns the number of roots
  
      def is_univariate(self):
          return True if self.number_of_variables==1 else False
  
      def number_of_roots(self):
          if self.is_univariate():
              return compute_number_of_roots(self) # This function returns the number of roots
          else:
              raise Exception(&quot;Number of roots is not defined for multivariate polynomials.&quot;)
  </code></pre>
  <p>Here, defining <code>p = Polynomial(3)</code> calling <code>p.number_of_roots()</code> raise the desired error, but when trying to get the attribute <code>p.nroots</code> an error that doesn't return a lot of information is given.</p>
  <p><strong>Taking into account the answers</strong> I think this is how it should be done:</p>
  <pre><code>class Polynomial:
      def __init__(self, number_of_variables:int):
          self.number_of_variables = number_of_variables
  
      def is_univariate(self):
          return True if self.number_of_variables==1 else False
  
      @property
      def nroots(self):
          if self.is_univariate():
              return compute_number_of_roots(self) # This function returns the number of roots
          else:
              raise Exception(&quot;Number of roots is not defined for multivariate polynomials.&quot;)
  </code></pre>