A detailed view of how we can use access modifiers in Python
Photo by Dayne Topkin on Unsplash
Object-oriented languages, like C++ and Java, use various keywords to control and restrict the resource usage of a class.
This is where keywords like public, privateand protected come into the picture. However, Python has a different way of providing the functionality of these access modifiers.
public members of a class are available to everyone. So they can be accessed from outside the class and also by other classes too.
Output of a public-access modifier
All members of a class are by default public in Python. These members can be accessed outside of the class, and their values can be modified too.
protected members of a class can be accessed by other members within the class and are also available to their subclasses.
No other entity can access these members. In order to do so, they can inherit the parent class. Python has a unique convention to make a member protected: Add a prefix _ (single underscore). This prevents its usage by outside entities unless it is a subclass.
Output of protected-access modifier
However, this doesn?t fully perform the functionality of the protected modifier. The attribute defined in the above program is accessible outside the class scope. It can also be modified as well.
Output of protected attribute modified
The private members of a class are only accessible within the class. In Python, a private member can be defined by using a prefix __ (double underscore).
Output of private- access modifier
So, in the private modifier?s case, we cannot access the attribute. So is a private modifier the way ahead?
The answer would be No
Python performs name mangling on private attributes. Every member with a double underscore will be changed to _object._class__variable.
Output of private attribute modified
Therefore, this proves Python provides you with access-modifiers functionality, but it can?t be compared to classical languages like C++ and Java. This practice entirely depends upon the programmer.
So a responsible programmer, upon seeing an attribute with such a naming convention, would refrain from accessing it outside its scope. This also wouldn?t be good to use in cases where fellow programmers aren?t aware of such naming conventions.
Do you think that python should have the entire functionality of access modifiers like C++ & Java? or Do you think it’s not that important?Leave your experiences and thoughts below!