[Tutor] Protected methods/variables
Kent Johnson
kent37 at tds.net
Tue Apr 4 19:43:01 CEST 2006
w chun wrote:
>> I have missed protected method/variables in Python. How do you declare
>> methods/variables used only by a class and their derived classes?
>
> hi KtalĂ ,
>
> welcome to Python! you missed "protection" in OOP with Python bceause
> there are no such declarations in Python!
>
> 1) there is a privacy *hint*, which is using "__" to start a variable
> or method name with, e.g., def __myMaybePrivateMethod(self,...).
> this does name-mangle the attribute at run-time, however the algorithm
> is fairly well-known and easy to crack:
> self._CLASS__myMaybePrivateMethod(). for more on this see,:
> http://docs.python.org/tut/node11.html#SECTION0011600000000000000000
1a) start a variable name with _ which is a hint to users of the class
that the variable is for internal use only.
> - you can use __slots__ to restrict arbirtrary creation of (dynamic)
> instrance attributes
You can do this, but it is generally considered a misuse of __slots__
and potentially problematic.
Python takes the attitude that "we're all adults here" and doesn't try
to hide anything. The _ naming convention is part of this culture - you
tell the users to keep hands off, but if they don't, on their head be it!
Kent
More information about the Tutor
mailing list