#1
  1. onCsdfeu
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Canada
    Posts
    100
    Rep Power
    12

    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
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2003
    Location
    Oregon
    Posts
    2
    Rep Power
    0
    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:
    import foo
    foo._bar


    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.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    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.
    Debian - because life's too short for worrying.
    Best. (Python.) IRC bot. ever.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    12
    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".

IMN logo majestic logo threadwatch logo seochat tools logo