On 4/14/07, James Stroud <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> But, if you have masochistic tendencies and want a lot of overhead in
> your programming, you can always bind yourself mercilessly to classes:
>
>
> class C(object):
>    declared = ['bob', 'carol', 'ted', 'alice']
>    def __setattr__(self, anattr, aval):
>      if anattr not in C.declared:
>        raise TypeError, "Just can't hook you up, bro."
>      else:
>        self.__dict__[anattr] = aval
>

You could also do this with __slots__, like:

>>> class C(object):
...     __slots__ = ['bob','carol','ted','alice']
...
>>> c = C()
>>> c.bob = 42
>>> c.bob
42
>>> c.x = 69
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'x'


although, I personally have never found the need nor desire to use __slots__



>
> E.g.:
>
> py> class C(object):
> ...   declared = ['bob', 'carol', 'ted', 'alice']
> ...   def __setattr__(self, anattr, aval):
> ...     if anattr not in C.declared:
> ...       raise TypeError, "Just can't hook you up, bro."
> ...     else:
> ...       self.__dict__[anattr] = aval
> ...
> py> c = C()
> py> c.bob = 42
> py> c.bob
> 42
> py> c.x = 69
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "<stdin>", line 5, in __setattr__
> TypeError: Just can't hook you up, bro.
>
>
> Extending this ugliness to type-checking is left as an exercise for the
> reader. Using metaclasses for such nonsense is left as an exercise for
> metaclass maniacs.
>
> James
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to