[Tutor] How to write protect attributes or names

Gregor Lingl glingl at aon.at
Tue Sep 16 20:05:39 EDT 2003


Alexandre Ratti schrieb:

> Hi Gregor,
>
>
> Gregor Lingl wrote:
>
>> is it possible to "write-protect" a definitive selection of attributes
>> (a) of a class
>> (b) of an object
>> (c) or a definitve selection of names of a module?
>> e.g. all the callable ones.
>
Hi Alexandre!
Thanks for your comments!

>
> For a class:
>
> 1) You could prefix your attribute names with two underscores so that 
> they cannot be (easily) accessed from outside of the class because of 
> the name-mangling feature. Example:

This IMHO is not what I need, as it not only write-protects
but also read-protects (i. e. makes the attribute sort of private)

>
> ....
> ['_Foo__bar']
> ##
>
> The attribute name is automatically modified so that it cannot be 
> easily modified.
>
> 2) You could also use properties (in Python 2.2+) to create read-only 
> attributes:

Hmmm..., interesting, but I want to write-protect methods, i.e. callable 
attributes. That will not
work with properties

>
> ##
> >>> class Foo(object):
> ...     def __init__(self):

> AttributeError: can't set attribute
> ##
>
> If you do not create a mathod to set the attribute value and pass it 
> in the property() call, then the attribute will be read-only.
>
> You could also try to override the "__setattr__" method in your class 
> to disallow settng specific attributes.

This will do what I want.

>
> I'm not sure what you can do at the module level.

Yes, I also have ordinary functions, eg
 >>> width(5)
which sets some hidden variable to 5
Now my program will also be used by very young students, who
probably sometimes write
 >>> width = 5
which will result in the function width not beeing acces2ible anymore
along with some (for them) strange errormessages like "int object is not 
callable"

But I fear, there is no way to write-protect functions in __main__'s 
namespace.

Regards, Gregor

>
>
> HTH.
>
> Alexandre
>
>
>
>
>
>





More information about the Tutor mailing list