Not possible to hide local variables

Ethan Furman ethan at stoneleaf.us
Tue Apr 28 09:56:09 CEST 2015


On 04/28, Cecil Westerhof wrote:
> If I remember correctly you can not hide variables of a class or make
> them read-only?
> 
> I want to rewrite my moving average to python. The init is:
>     def __init__(self, length):
>         if type(length) != int:
>             raise ParameterError, 'Parameter has to be an int'
>         if n < 0:
>             raise ValueError, 'Parameter should be greater or equal 2'
>         self.length             = length
>         self.old_values         = []
>         self.current_total      = 0
> 
> But when someone changes length, old_values, or current_total that
> would wreck havoc with my class instance. What is the best way to
> handle this?

Prefix those names with a single leading underscore, which is the convention
for private variables.

This way, if some user (maybe you! ;) has a good reason to change those
values in can be done, but it is quite clear that said user is mucking about
with internals and they are on their own.

--
~Ethan~



More information about the Python-list mailing list