_Prevent_ dynamic attribute addition?

Sean 'Shaleh' Perry shalehperry at attbi.com
Fri Aug 30 13:52:08 EDT 2002


On Friday 30 August 2002 10:37, Neil Schemenauer wrote:
> Robert Oschler wrote:
> > Is there a way to make a class 'non-modifiable', or am I just not
> > understanding something here?
>
> The new 2.2 __slots__ feature might help.  For example:
>     >>> class A(object):
>
>     ...     __slots__ = ['foo']
>     ...
>
>     >>> a = A()
>     >>> a.foo = 1
>     >>> a.foo
>
>     1
>
>     >>> a.bar = 2
>
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>     AttributeError: 'A' object has no attribute 'bar'
>

So in other words, if you define __slots__ *ONLY* those members can exist.  
Keen.




More information about the Python-list mailing list