counter part of __getattr__
<p>I am trying to find a way to set <code>dict</code> values encapsulated into a <code>class</code>, for example using <code>__getattr__</code> i can return the internal <code>dict</code> value, however the <code>__setattr__</code> is called even when attributes exists, making my implementation ugly. The example below is simplified my actual class inherits from a <code>Subject</code> <code>class</code> (the subject part of the observer pattern)</p>

<p>i am trying to achieve something like this:</p>

<pre><code>obj = Example()
obj.username = 'spidername' # all OK username is a key in the internal dict
# but company is not a key in the internal dict so
obj.company = 'ABC' # will raise AttributeError
</code></pre>

<p>and i am asking if there is a better way than the way i am doing below:    </p>

<pre><code>class Example(object):
    def __init__(self, table=None):
        self._fields = {}
        self._table = table

    def _set_fields(self):
        """
        this method will be implemented by 
        subclasses and used to set fields names and values
        i.e.
        self._field['username'] = Field(default='unknown', is_primary=False)
        """
        raise NotImplementedError

    def __getattr__(self, name):
        """
        great this method is only called when "name"
        is not an attribute of this class
        """
        if name in self._fields:
            return self._fields[name].value
        return None

    def __setattr__(self, name, value):
        """
        not so great, this method is called even for
        attributes that exists in this class

        is there a better way to do the following?             
        this can be in __init__, but its still ugly
        """
        attribs = ['_fields', '_table'] 
        if name in attribs:
            super(Example, self).__setattr__(name, value)
        else:
            if name in self._fields:
                self._fields[name].value = value
            else:
                raise AttributeError
</code></pre>

<p>EDIT: adjusted comment in code, added missin quotes                  </p>
