_Prevent_ dynamic attribute addition?

Robin Becker robin at jessikat.fsnet.co.uk
Fri Aug 30 13:43:05 EDT 2002


In article <OINb9.106612$%v4.5563282 at e3500-atl2.usenetserver.com>, Robert Oschler
<Oschler at earthlink.net> writes
>Python newbie here, using Python 2.2.2 on a SuSE Linux box.  There's a
>feature in Python I find very powerful but a bit disconcerting, the ability
>to add new attributes to a class object dynamically.  Is there a way to make
>a class 'non-modifiable' in that sense, without losing the ability to
>further derive from it?  Here's a scenario that describes my concern:
>
>Let's say I have two classes A and B.  A has a data member called
>NumberOfMonkeys and B does not.  I write tons of code and lots of it uses
>A.NumberOfMonkeys.  Later I realize that NumberOfMonkeys really belongs in
>Class B so I delete it from A's class declaration and move it into B's.  All
>the dependent code that used to manipulate the value of the existing
>NumberOfMonkeys attribute will now be adding the NumberOfMonkeys attribute
>dynamically to Class A.  I would an error to be thrown instead so, so I can
>fix/update the code.  I know I can check for the existence of an attribute
>on an object, but that sounds pretty cumbersome to do that before any and
>every use of an attribute.
>
>Is there a way to make a class 'non-modifiable', or am I just not
>understanding something here?
>
>thx
>
>
>
>
with 2.2 you can use slots

>>> class A(object):
...     __slots__=('a',)
...     def __init__(self):
...             self.a = 1
... 
>>> a=A()
>>> a.b
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'A' object has no attribute 'b'
>>> a.b=2
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'A' object has no attribute 'b'
>>> a.a=33
>>> 


-- 
Robin Becker



More information about the Python-list mailing list