Hello Pythonistas!
Today we will learn how to create private and protected members in Python. Actually, python has no access modifiers by default all the members are public. But we can achieve the same using _(underscore) and __(double underscore). Let us check this with an example
Code
class Parent:
public = "public"
_protected = "protected"
__private = "private"
def print_all_members(self):
print("Public: ", self.public)
print("protected", self._protected)
print("private", self.__private)
a = Parent()
a.print_all_members()
print(a.public)
print(a._protected)
print(a.__private)
Output
Public: public
protected protected
private private
public
protected
Traceback (most recent call last):
File "/home/afsal/Desktop/experiments/PYTHON_EXPERIMENT/python_experiments/access_modifiers.py", line 20, in <module>
print(a.__private)
AttributeError: 'Parent' object has no attribute '__private'
In Python if we sees name starts with underscore here in this example _protected is an indication to developers that this is internal to the class. But still, we can access the member directly using an object. The __private member is not accessible outside. If we access this will raise an attribute error. But still, we can access this in another way, If we analyze the class using dir we can see that _Parent__private field. We can access the field easily. If a python class sees a double underscore it will automatically convert the name to _<classname><privatevariable> It is called name mangling
code
print(dir(a))
print(a._Parent__private)
output
['_Parent__private', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_protected', 'print_all_members', 'public']
private
Takeaway
- In python actually, there are no access modifiers
- A protected member can be defined with _
- A protected member is only an indication to developers but still can access
- Private can be defined using __
- Private can still access outside using its mangled name
Hope you have learned something from this post. Please share your comments at afsal@parseltongue.co.in