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


Groups > comp.lang.python > #36978 > unrolled thread

Re: To make a method or attribute private

Started byLie Ryan <lie.1296@gmail.com>
First post2013-01-18 18:46 +1100
Last post2013-01-18 18:46 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: To make a method or attribute private Lie Ryan <lie.1296@gmail.com> - 2013-01-18 18:46 +1100

#36978 — Re: To make a method or attribute private

FromLie Ryan <lie.1296@gmail.com>
Date2013-01-18 18:46 +1100
SubjectRe: To make a method or attribute private
Message-ID<mailman.613.1358495230.2939.python-list@python.org>
On 17/01/13 11:34, iMath wrote:
> 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 .

Python does not have a REAL private methods/attributes. The double 
leading underscore is meant to trigger name mangling to avoid naming 
collisions with subclasses, the method/attribute is still accessible 
using the mangled name:

 >>> ap._A__a
'__a'

You generally only use double leading underscores when your private 
method/attribute is in a very high risk of having naming clashes with 
superclasses/subclasses.

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

We're all consenting adults. Use methods/attributes with single or 
double leading underscore at your own risk.

Most programming languages do not actually have a private attribute that 
is totally inaccessible from outside, there are usually ways work around 
access restrictions, usually using reflections or pointers. Python only 
makes it easy to do so by making private variables only a convention.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web