Try Catch errors when setting attributes
<p>Is there a rule of thumb to follow for error catching while setting attributes of an object? Let's say for example that you have a Shape class as follows:</p>

<pre><code>class Shape():
    def __init__(self, size):
        self.size = size
</code></pre>

<p>I can do the following:</p>

<blockquote>
  <p>>>> s = Shape(3)</p>
  
  <p>>>> s.size</p>
  
  <p>3</p>
  
  <p>>>> s.size = "hello"</p>
  
  <p>>>> s.size</p>
  
  <p>'hello'</p>
</blockquote>

<p>But what if the attribute must be numeric? How do I catch TypeErrors in this situation? Do I put a try/except inside the <strong>init</strong> definition? This is my guess:</p>

<pre><code>class Shape():
def __init__(self, size):
    try:
        float(size)
        self.size = size
    except:
        raise TypeError, "Value must be numeric"
</code></pre>

<p>This will catch the error on initialization but not when setting the attribute. How do I catch a TypeError when the user tries s.size = "hello" ?</p>

<p>Thank you!</p>

<p>I tried implementing the answer below and it didn't work:</p>

<pre><code>class Shape():
def __init(self, size):
    self.size = size

@property
def size(self):
    return self._size

@size.setter
def size(self, value):
    self._size = float(value)
</code></pre>

<p>I get the following error message:</p>

<blockquote>
  <p>Traceback (most recent call last):   File "python_playground.py", line 18, in </p>

<pre><code>print s.size   File "python_playground.py", line 9, in size

return self._size AttributeError: Shape instance has no attribute '_size'
</code></pre>
</blockquote>
