howto prevent class variable assignment
Uwe Mayer
merkosh at hadiko.de
Sun Feb 1 09:11:06 EST 2004
Hi,
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?
Here some example code:
>>> class A(object):
... cInt = 5
... cList = [1,2,3]
... def __init__(self):
... self.cInt = 6
...
>>> a = A()
>>> a.cInt
6
>>> a.__class__.cInt
5
>>> a.cList[2] = 5 #<-- prevent this
>>> a.cList
[1, 2, 5]
>>> a.cInt = 42 #<-- allow this
>>> a.cInt
42
>>> a.__class__.cInt
5
>>>A.cInt = 10 #<-- prevent this
I tried to overwrite __setattr__(self, name, value) method, but this is only
called if I call it on an instance, i.e.
>>> a.cInt = 5
but not when I call it on the class:
>>> A.cInt = 10
Can anyone give me some pointers or suggentions how to handle this?
Thanks
Uwe
More information about the Python-list
mailing list