Encapsulation unpythonic?

Fabrice Pombet fp2161 at gmail.com
Fri Aug 30 13:43:28 EDT 2013


On Saturday, August 17, 2013 2:26:32 PM UTC+2, Fernando Saldanha wrote:
> I am new to Python, with experience in Java, C++ and R. 
> 
> 
> 
> As I understand encapsulation is not a big thing in the Python world. I read that you can put two underscores before the name of a variable within a class declaration but in the many examples of code I looked at this is not widely used. I also read that encapsulation is "unpythonic."
> 
> 
> 
> Questions:
> 
> 
> 2) If it is in fact true that encapsulation is rarely used, how do I deal with the fact that other programmers can easily alter the values of members of my classes?
> 
Fernando, it is widely accepted that Python pays very little attention to encapsulation as a principle set in stone. Chaz's definition of encapsulation is also mine. Now you need to consider that taking this principle off the hostel of OOP does not mean that you can do whatever you fancy and you can't make anything unsettable.

There are plenty of techniques within Python that allow you to protect your arguments (in particular, decorators) inside a Class.

Now, lets get to the pretentious philosophical discussion: I guess encapsulation is quite the opposite of, say, dynamic typing, which is arguably core in Python. In practice this allows Python to be less verbose: at the end of the day, if you look back at your previous languages, don't you find that some of their compulsory features are usually more of a pain than something useful in practice? And after all, whither encapsulation? Can't we just have objects whose arguments are determined externally if we want to?
And that is the ballgame: as my old tutor says: "the claptrap of setters and getters does not need to be here if it is unnecessary". I would add: "so long as you can have them when you deem it necessary", and Python allows that.




More information about the Python-list mailing list