0

Can you explain why private class names are mangling. Consider the following class:

class A:
    __a=32
    def func():
        return a

__a is a private field of the class here. But what sence of renaming __a to _A__a? I dont understand what a sence of methods in python if we can't access from this body to class field?

Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • 2
    Python doesn't have private fields, it has name-mangling. If you don't want name-mangling, don't use names that begin with a double-underscore. – BrenBarn Feb 27 '14 at 05:48
  • @BrenBarn From python reference manual: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a **private name** of that class. –  Feb 27 '14 at 05:49
  • 2
    @DmitryFucintv it's "considered", by convension, but not really "private" – zhangxaochen Feb 27 '14 at 05:50

1 Answers1

4

The purpose of name mangling is to prevent accidental name collisions from defining the same attribute in a subclass. Note that this has nothing to do with preventing access to the attribute. If you want to pretend that language level access control is a meaningful security boundary, go use some other language. Python's motto is that "we're all consenting adults".

Anyway, your example does work once you correct the syntax.

class A(object):
    __a = 32
    def func(self):
        return self.__a

class B(A):
    __a = 41
    def bar(self):
        return self.__a

    def bar2(self):
        return self._A__a

print A().func()
print B().func()
print B().bar()
print B().bar2()

B().func() still prints out 32, because it is accessing the version of __a defined in class A.

Antimony
  • 37,781
  • 10
  • 100
  • 107
  • +1 for the good explanation. In addition this can be useful: http://stackoverflow.com/questions/6930144/underscore-vs-double-underscore-with-variables-and-methods – Colin Bernet Feb 27 '14 at 06:35