Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How/Why does this work in python? rover._Dog__password()

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?

like image 991
Aufwind Avatar asked Dec 01 '25 13:12

Aufwind


1 Answers

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?

like image 99
Sandro Munda Avatar answered Dec 04 '25 06:12

Sandro Munda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!