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


Groups > comp.lang.python > #37107

To make a method or attribute private

Newsgroups comp.lang.python
Date 2013-01-20 01:17 -0800
Message-ID <8adf7e6a-e16a-4d81-8e0d-6339bb4f117c@googlegroups.com> (permalink)
Subject To make a method or attribute private
From iMath <redstone-cold@163.com>

Show all headers | View raw


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?

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


Thread

To make a method or attribute private iMath <redstone-cold@163.com> - 2013-01-20 01:17 -0800
  Re: To make a method or attribute private Chris Angelico <rosuav@gmail.com> - 2013-01-20 20:23 +1100
    Re: To make a method or attribute private alex23 <wuwei23@gmail.com> - 2013-01-20 15:14 -0800
      Re: To make a method or attribute private Dave Angel <d@davea.name> - 2013-01-20 18:32 -0500
        Re: To make a method or attribute private alex23 <wuwei23@gmail.com> - 2013-01-20 18:24 -0800
          Re: To make a method or attribute private Mitya Sirenef <msirenef@lightbird.net> - 2013-01-20 21:45 -0500

csiph-web