CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Python – Access Modifiers – Private Name Mangling

There are NO Access Modifiers in Python. Yes, what you READ is CORRECT. Python doesn’t have any Access Specifiers defined. All the defined members can access from anywhere in the program, within the defined scope.

Some of the Programming Languages (C++, Java, C# etc,.) provides private, protected & public access modifiers to define the access boundaries. That said, these languages, doesn’t allow to access the members outside the access boundaries. private restricts the access to within the defined class, protected extends the access to derived class and public modifier gives the freedom to access the members outside of the classes.

In Python, there are NO restrictions to access the members. But Python uses name mangling to define private names; this way we can restrict the members to access; don’t worry, these also can be accessible with special care.

Private Name Mangling

The members prefixed with two or more underscores (“__”) called as private names. Python treats them separately; it doesn’t allow to access the members directly; but allowed to access them with special care. If we attempt to access the private names directly; Python will throw the AttributeError. Why this Error? Because, when you define a member prefixed with two or more underscores (“__”); Python internally mangling the name by adding class name prefixed with single underscore (“_”).

For example, the class A has a member __msg can be mangled as _A__msg. If we directly access _msg; there is NO name defined (because already mangled) and we see an AttributeError.

This is the way we can define our members as private members. Here is a working example demonstrate this behavior.

>>> class A:
...    __msg = "Hello!"
...    msg = "Hi!"
... 
>>> A
<class '__main__.A'>
>>> a = A()
>>> a.__msg
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute '__msg'
>>> a._A__msg
'Hello!'
>>> a.msg
'Hi!'
>>>

We will discuss more topics as we go.

/Shijit/

Python – Access Modifiers – Private Name Mangling

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top