user2953119
user2953119

Reputation:

What is the sense of private names in a class

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?

Upvotes: 0

Views: 93

Answers (1)

Antimony
Antimony

Reputation: 39451

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.

Upvotes: 4

Related Questions