How to prevent illegal definition of a variable in objects?

Bernhard Herzog herzog at online.de
Thu Jun 15 08:40:15 EDT 2000


"Daehyok Shin" <sdhyok at email.unc.edu> writes:

> Maybe a little better, but not enough good.

What's missing?
 
> class A:
>  x = 1

What's this class variable good for if you override it in the
constructor anyway?

>  def __init__(self):
>    self.__dict__["x"]=1
> 
>  def __setattr__(self, name, value):
>   if not self.__dict__.has_key(name):
>    raise AttriubuteError
>   else:
>    self.__dict__[name] = value
> 
>  def __getattr__(self, name):
>   try:
>    return self.__dict__[name]
>   except KeyError:
>    raise AttriubuteError

This __getattr__ implementation does exactly what happens by default
anyway (modulo the misspelling of AttributeError) and is therefore
completely redundant. After all, if self.__dict__ contains name,
__getattr__ will not be called. That also means that in general you
don't have to have to use self.__dict__ to access instance variables in
__getattr__.

-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list