Python and Private Class Members

It's Private or is it really ?šŸ˜’



Python is a great language and one can easily pick it up and make wonders using it. It's easy and quite lucid to understand. Though many have the opinion that it is a functional language while others convicted it as an object-oriented language. Personally, I think it's a blend of both worlds.

So, well as the heading of this blog suggests, we are going to explore python and private access modifiers. As most of us know that private access specifiers restrict members(attributes and methods) from being seen or accessed outside of their own region (class).  

Consider the normal NameCollector class which collects the name in name_collection list. This is a typical example where you can see that the name_collection can be accessed or modified outside of the class pretty easily.

With a little trick of adding dunder(double underscore __) in the prefix of name_collection (__name_collection), python would make the __name_collection inaccessible outside the scope of the class. While trying to execute the below code, you will get an attribute error at line 17, as __name_collection is restricted outside the scope of a class.


But, hold on your horses. Python has its own way of making class members private. It usually wraps the private member in an abstract wrapper that is hard to be seen outside of the class. Aaaaand...... we can still access the private class members outside their scope using __dict__ built-in class attribute.


__dict__ provide us the alias to access the members of the class that has been shadowed by the python interpreter. In my case __name_collected has an alias of _NameCollector__name_collection. In your case, it might be different. So comment like 21 before executing code snippet number 3 and once you get your alias name to uncomment line 21, add your alias name in place of _NameCollector__name_collection and run your code again.

Those coming from the background of using high-level languages like Java, C#, C++, etc might find it strange that python disguises their private members under the hood. I too had my share of concerns, however, it hardly matters because each language has its own merits and downsides, And there are a plethora of languages and frameworks around us these days.  Also, it does not mean that we cannot create a secure application using python. Many commercial large-scale applications these days are often the mix-collaboration of different small components develop with different frameworks and languages.

Python is still one of the great languages out there and we can be benefited from what it has to offer and make use of its merits. Just remember, there is no perfect language!

                                    (Image Credit : Vidar Kristiansen From Unsplash)


Comments