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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With