Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #36922

To make a method or attribute private

From "iMath" <2281570025@qq.com>
Subject To make a method or attribute private
Date 2013-01-17 08:34 +0800
Newsgroups comp.lang.python
Message-ID <mailman.584.1358382936.2939.python-list@python.org> (permalink)

Show all headers | View raw


<div><div>To make a method or attribute private (inaccessible from the outside), simply start its&nbsp;</div><div>name with two underscores</div><div><br></div><div>----《Beginning Python From Novice to Professional》</div><div><br></div><div>but there is another saying goes:</div><div>Beginning a variable name with a single underscore indicates that the variable should be treated as ‘private’.</div><div><br></div><div>I test both these 2 rules ,it seems only names that start with two underscores are REAL private methods or attributes .</div><div><br></div><div>&gt;&gt;&gt; class A:</div><div>... &nbsp; &nbsp; def __init__(self):</div><div>... &nbsp; &nbsp; &nbsp; &nbsp; self.a = 'a'</div><div>... &nbsp; &nbsp; &nbsp; &nbsp; self._a = '_a'</div><div>... &nbsp; &nbsp; &nbsp; &nbsp; self.__a = '__a'</div><div>...</div><div><br></div><div><br></div><div><br></div><div>&gt;&gt;&gt; ap = A()</div><div>&gt;&gt;&gt; ap.a</div><div>'a'</div><div>&gt;&gt;&gt; ap._a</div><div>'_a'</div><div>&gt;&gt;&gt; ap.__a</div><div>Traceback (most recent call last):</div><div>&nbsp; File "&lt;stdin&gt;", line 1, in ?</div><div>AttributeError: A instance has no attribute '__a'</div><div><br></div><div>so what is your opinion about single leading underscore and private methods or attributes?</div></div>

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

To make a method or attribute private  "iMath" <2281570025@qq.com> - 2013-01-17 08:34 +0800
  Re: To make a method or attribute private alex23 <wuwei23@gmail.com> - 2013-01-16 17:04 -0800
    Re: To make a method or attribute private iMath <redstone-cold@163.com> - 2013-01-20 06:52 -0800
      Re: To make a method or attribute private Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-20 15:15 +0000
  Re: To make a method or attribute private Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-17 02:38 +0000
  Re: To make a method or attribute private iMath <redstone-cold@163.com> - 2013-01-20 17:14 -0800
    Re: To make a method or attribute private Chris Angelico <rosuav@gmail.com> - 2013-01-21 12:26 +1100
    Re: To make a method or attribute private Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-21 03:27 +0000
      Re: To make a method or attribute private Chris Angelico <rosuav@gmail.com> - 2013-01-21 15:46 +1100
        Re: To make a method or attribute private alex23 <wuwei23@gmail.com> - 2013-01-20 21:44 -0800

csiph-web