howto prevent class variable assignment

Michele Simionato michele.simionato at poste.it
Sun Feb 1 14:28:08 EST 2004


Gerrit Holl <gerrit at nl.linux.org> wrote in message news:<mailman.1096.1075646941.12720.python-list at python.org>...
> Uwe Mayer wrote:
> > when an instance variable of a class is not found, python tries to fall back
> > to the class variable. 
> > I want to use that feature to provide default settings for a class which can
> > be overwritten by assignments to variables with the same name.
> > 
> > This quickly becomes difficult to handle when you get confused wether your
> > assignment was made to a class variable or an instance variable. I
> > therefore want to prevent write access to class variables. How do I do
> > that?
> 
> I think you can do that with a Metaclass.
> See http://www.python.org/2.2.2/descrintro.html#metaclasses
> 
> Gerrit.
> 

Indeed. You must override __setattr__ in the metaclass of your class.
For instance

>>> class C:
...     class __metaclass__(type):
...         def __setattr__(cls,name,value):
...             raise "error"
...
>>> C.x = 1 # error



More information about the Python-list mailing list