3

I am doing the python koan (for python 2.6) and ecnountered something I don't understand. One of the files has the following code in line 160:

class Dog(object):
    def __password(self):
        return 'password'

This

rover = Dog()
password = rover.__password()

results in an AttributeError. That is clear to me. (__password(self) is some kind of private method because of the leading two underscores).

But this

rover._Dog__password()

is a mystery to me. Could some one please explain to me how or why this works or better point me to the docs where this is described?

Aufwind
  • 25,310
  • 38
  • 109
  • 154

2 Answers2

7

Double underscore :

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

So when you call the __methodname, it's exactly a call to _classname__methodname. The result is an AttributeError

Single underscore :

Variables in a class with a leading underscore are simply to indicate to other programmers that the variable should be private. However, nothing special is done with the variable itself.

Python documentation here :

Python private variables documentation

Complete post found here :

What is the meaning of a single- and a double-underscore before an object name?

Community
  • 1
  • 1
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
  • No reference or other context for the quote. – Marcin Jan 15 '12 at 13:17
  • The quote is old; the current version of http://docs.python.org/tutorial/classes.html#private-variables words it more succinctly. – Petr Viktorin Jan 15 '12 at 13:28
  • Thank you for your answer. But when I do `rover.__password()` it results in an `AttributeError`. But when I do `rover._Dog__password()` it returns the password. No `AttributeError` raised. – Aufwind Jan 15 '12 at 16:41
0

Python does name-mangling of methods that begin with a double-underscore, such that it comes out as you see above. This prevents name clashes in inheritance hierarchies, but does not actually prevent a programmer from invoking the mangled name directly.

Marcin
  • 48,559
  • 18
  • 128
  • 201