Here’s a couple of quotes I gathered from a simple stroll around stackoverflow:
– Academic world: “Encapsulation ensures the safety of your code”
– CS world: “Encapsulation is a neat pattern to avoid bugs and ease readability.”
– Production world: “You’re not trying to add security by encapsulation, ARE YOU?”
– Python world: “We are all adults. Feel free to shoot yourself in the foot if you must.”
You see, back when I was beginning with Python, I thought that encapsulation was an oppressive idea, fit to languages like Java that only seemed to make life difficult for programmers. But as I ease my mind into the possibility of enterprise scale development, the merits of encapsulation as a pattern become evident. Still, I do hate having to write two line getters and setters in Java.
So, does python have encapsulation? Of course it does:
– It’d seem that all class variables are public in Python. Not so. The variables live inside the object’s dict. What Python does is that it gives you default public getters and setters with neat syntax, and that’s all you need in the majority of cases. Need some specialized behavior? Just use property and override getters and setters with your own.
– Then there is encapsulation by convention. Don’t want someone accessing something from the outside? Prepend with single underscore. Someone REALLY shouldn’t rely on an implementation detail? Use double underscores which also mangles the name. There’s protected and private for you. Sure, no-one can really stop you from peaking inside and messing things up. But this convention is so strong in python that if you do, by design or mistake and not with a very, very good excuse, you might as well forfeit your pythonic license.
Python basically says: You are an adult, act like it. And treat others like adults too. But the pattern is still there.