3

Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python

I had a question when I was reading the python documentation on private variables link.

So the documentation tells that it is a convention to name private variables with an underscore but python does not make the field private.

>>> class a():
      def __init__(self):
         self.public = 11
         self._priv = 12
>>> b = a()
>>> print b._priv
>>> 12

I wanted to know if there is a way in which I can make a variable "truly" private in python.

Community
  • 1
  • 1
veepsk
  • 1,703
  • 3
  • 14
  • 21
  • In the link you mentioned, there is no specific mention of class members, it is a general question about private methods and variables. – veepsk Jan 05 '13 at 06:38
  • As you can probably see now, in addition to first reading the Python documentation (bravo!), it's often very useful to search StackOverflow for similar questions before posting your own. The same is true for posting answers, but even fewer people do that. – martineau Jan 05 '13 at 14:35

3 Answers3

8
  • Guido van Rossum put it: we are all adults.
  • The extended version: We are all adults. Feel free to shoot yourself in the foot if you must.

You can hide it a bit if you must, but you really shoudn't:

class NonAdult(object):
    def __init__(self):
        self.__private_number = '42'
    def __getattr__(self, name):
        if name.startswith('__private'):
            raise AttributeError

if __name__ == '__main__':
    na = NonAdult()
    print(na.__private_number) # raises AttributeError
    print(na.__dict__['_NonAdult__private_number']) # would still return 42
miku
  • 181,842
  • 47
  • 306
  • 310
5

No, there are no private variables or methods in Python objects. The phrase "We're all consenting adults here" is generally used to explain that they are seen as unnecessary.

A single underscore is sometimes used for "private" members, buy only as a convention; it serves no functional purpose.

Leading double underscores cause name mangling, but are only intended to avoid naming collisions in subclasses. It does not provide any "private member safety", as you can still get to them.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
0

You can use a double leading underscore to invoke Pythons name mangling. So __priv becomes _MyClass__priv. It will still be accessible, but prevents subclasses from accidental overriding.

John Brodie
  • 5,909
  • 1
  • 19
  • 29