Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actual implementation of private variables in python class [duplicate]

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.

like image 481
veepsk Avatar asked Sep 14 '25 23:09

veepsk


2 Answers

  • 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
like image 172
miku Avatar answered Sep 17 '25 11:09

miku


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.

like image 43
Jonathon Reinhart Avatar answered Sep 17 '25 12:09

Jonathon Reinhart