How to prevent illegal definition of a variable in objects?

Jeff Senn senn at maya.com
Fri Jun 16 09:01:59 EDT 2000


Roland Schlenker <rol9999 at attglobal.net> writes:
> How about this;
> 
> >>> class A:
> ...     def __init__(self):
> ...         self.x = 1
> ...     def __setattr__(self, name, value):
> ...         if name == "x":
> ...             self.__dict__[name] = value
> ...         else:
> ...             raise AttributeError

Or if (as I suspect) the goal is to "protect" the object from getting
new, different attributes after it has been initialized (e.g. from
outside the "class") you could do something like this:

class A:
     def __init__(self):
         self.x = 1
         self.foo = 'bar'
         ...other initialization...
         self._protect = 1           # <-- always last line of __init__
     def __setattr__(self, n, v):
         if not self.__dict__.has_key('_protect') or self.__dict__.has_key(n):
             self.__dict__[n] = v
         else:
             raise error("Protected Object") #or whatever

...a way to prevent someone from deleting attributes left as an
exercise to the reader... :-)

-- 
-Jas





More information about the Python-list mailing list