Changing the private variables content

David Stanek dstanek at dstanek.com
Tue Jul 21 22:05:46 EDT 2009


On Tue, Jul 21, 2009 at 6:00 PM, Rhodri
James<rhodri at wildebst.demon.co.uk> wrote:
> On Tue, 21 Jul 2009 21:55:18 +0100, Ryniek90 <ryniek90 at gmail.com> wrote:
>
>> Hi.
>> I'm writing some class, and decided to use inside private method and some
>> private variables. While with method i haven't got any problem's with
>> variables i have.
>
> There is no mechanism in Python that makes attributes truly private.
> self._number is an attribute just like any other, the whole business
> with _leading_underscores is purely a matter of convention.  If you
> have an instance attribute or method with a leading underscore, you
> know that using it or calling it isn't something you're supposed
> to do outside its class, but nothing will stop you doing exactly that
> if you're rude enough to try.
>

Doubling the _ will give you a little more privacy. It really just
mangles the attribute name, but it close to what you want.

I just use a _single_under to tell other programmers that they
shouldn't be accessing that attribute directly. To my knowledge
nothing bad has happened because things are public and using the
__double_under makes testing a little harder.

  >>> class C(object):
  ...     def __init__(self):
  ...         self.__x = 0
  ...
  >>> c = C()
  >>> c.__x
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  AttributeError: 'C' object has no attribute '__x'
  >>> c._C__x
  0


-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek



More information about the Python-list mailing list