To make a method or attribute private

iMath redstone-cold at 163.com
Sun Jan 20 04:17:34 EST 2013


To make a method or attribute private (inaccessible from the outside), simply start its
name with two underscores

----《Beginning Python From Novice to Professional》

but there is another saying goes:
Beginning a variable name with a single underscore indicates that the variable should be treated as ‘private’.

I test both these 2 rules ,it seems only names that start with two underscores are REAL private methods or attributes .

>>> class A:
...     def __init__(self):
...         self.a = 'a'
...         self._a = '_a'
...         self.__a = '__a'
...



>>> ap = A()
>>> ap.a
'a'
>>> ap._a
'_a'
>>> ap.__a
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute '__a'

so what is your opinion about single leading underscore and private methods or attributes?



More information about the Python-list mailing list