Not possible to hide local variables
Cecil at decebal.nl
Wed Apr 29 08:32:10 CEST 2015
Op Tuesday 28 Apr 2015 10:37 CEST schreef Steven D'Aprano:
> On Tuesday 28 April 2015 17:33, Cecil Westerhof wrote:
>> If I remember correctly you can not hide variables of a class or
>> make them read-only?
> In Python circles, the preferred terminology for class and instance
> members is "attributes" rather than variables. "Variable" is
> reserved for module- and function-level name bindings.
I will try to remember that.
> But other than that, you are correct. Python practices attribute
> hiding by convention. Names beginning with a single underscore like
> _spam or obj._eggs are treated as private.
Using that now.
> Names beginning with two underscores, but not trailing with
> underscores, are also name-mangled: obj.__eggs will be mangled to
> obj._TheClass__eggs. You should avoid name-mangling unless you
> really need it, don't use it "just in case".
What is a good reason?
> The convention is, if the caller messes with your private attributes
> or variables, and their code breaks, they have nobody to blame but
> themselves, and we are allowed to laugh at them. We're consenting
> adults here.
Coming from C/C++ and Java I have to get used to it, but I will manage
> Don't use a class at all. Moving average is best handled as a
> generator. We can use a regular generator:
Not in this case. The idea is that you do not know the elements at the
moment, but feed them to the MovingAverage instance as they come in.
> If you must use a class, flag the internal attributes as private
> with a leading underscore. Your callers will respect that, and if
> they don't, all promises are null and void.
Senior Software Engineer
More information about the Python-list