December 30th, 2003, 03:52 PM
My class' privacy !
Damn, I was re-re-reading Eckel's "Thinking in C++" when I asked myself "Damn, are there any private and/or protected keywords in Python ?" I just hadn't done much OOP using Python. And no, private and protected aren't keywords in Python.
So, is there any way to create a class with protected and private members ?
Time is the greatest of teachers ; sadly, it kills all of its students.
- Hector Berlioz
December 30th, 2003, 05:33 PM
The short answer is sort of.
If you start a name with an underscore, it won't be imported when you say:
from foo import *
but it can still be accessed with:
A class member starting with a double underscore has its name (as seen outside the class) mangled to something like __ClassName__memberName.
I can't remember exactly, check the python docs.
So the long and the short of it is that you can tell people not to use your private members, but you can't stop them if they want to ignore you.
December 31st, 2003, 11:14 AM
filerba covered the finer points, but I just wanted to mention that the philosophy behind this is this: programmers know better what they want to do with the code that you provide than you do. It's a more "social" way of doing it whereas private/protected is a more guarded way of doing it. I vastly prefer Python's way of doing it because it simply makes more sense to me that I would know what I want to do better than someone else would. Granted, I may be misguided and may not be able to do what I want to with the given code, but that should be my problem and not the problem of the person providing that code. To me, in the end everybody wins with this scheme.
December 31st, 2003, 09:11 PM
But, of course, it is possible to provide an environment where the end developer is severely inconvenienced through the use of metaclass programming. So, in theory, it is possible to create a private place within Python, if your absolutely feel a need to. In the end though, that need you may feel is often a product of an indoctrination where you have been taught that the only way to ensure proper usage of your libraries is to force a specific usage, rather that to encourage a specific usage, as is the "Python way".