0

If I run this in Python

class Boo(object):
    def __init__(self, x):
        self._x = x
        self.__bingo = 3
        self._info = {'x': x, 'y':42}
    def __dir__(self):
        return ['x']
    @property
    def x(self):
        return self._x
    @property
    def z(self):
        return self._x+1
    def __getattr__(self, key):
        return self._info[key]

b = Boo(44)
b.__dict__.keys()

then it prints

['_info', '_Boo__bingo', '_x']

Why does __bingo get renamed? Are double-underscore attributes reserved?

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • Because that's *exactly what you told Python to do*. Where did you get the idea to use double-underscores? Did you just stumble upon this behavior? Or have you been following some tutorial that tells you double-underscores are "private"? – juanpa.arrivillaga Oct 18 '17 at 00:10
  • I have no problem with this being marked as a duplicate, but the [linked question](https://stackoverflow.com/questions/7456807/python-name-mangling) is only tangentially related to this question. There is [an answer in that question](https://stackoverflow.com/a/34903236/44330) that does answer my question. – Jason S Oct 18 '17 at 02:27
  • @juanpa.arrivillaga I stumbled upon this behavior, and wanted to know why, which is exactly what my question states. (Your comment comes across as somewhat arrogant, by the way.) – Jason S Oct 18 '17 at 02:35
  • It was an honest question. There are, unfortunately, a lot of Python tutorials, and at least a couple of text-books, that tell people to use double-underscore name-mangling like one would the private access modifier in Java or C++. – juanpa.arrivillaga Oct 18 '17 at 03:16
  • Oh, ok. The reason I considered using it was a separate issue (which I may ask when I have a chance -- unfortunately this community does not tolerate questions that are meandering, which is exactly what happens in real life when someone is trying to understand something that is unclear to them, so the only way I'll ask is if I have the time to focus and ask it carefully.) – Jason S Oct 18 '17 at 04:05

1 Answers1

2

It has to do with mangling, something python's interpreter does. Here's an article about it.

https://shahriar.svbtle.com/underscores-in-python

Austin A
  • 566
  • 2
  • 15
  • 1
    ah, ok here's the item in the docs: https://docs.python.org/2.7/tutorial/classes.html#tut-private – Jason S Oct 18 '17 at 02:29