To make a method or attribute private

iMath redstone-cold at 163.com
Mon Jan 21 02:14:36 CET 2013


在 2013年1月17日星期四UTC+8上午8时34分22秒,iMath写道:
> 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?

so there is no REAL private variable in Python but conversion exists in it that python programmer should follow and recognize .right ?



More information about the Python-list mailing list