About classes and OOP in Python

Roy Smith roy at panix.com
Mon Apr 10 11:37:16 EDT 2006


"fyhuang" <fyhuang at gmail.com> wrote:
> I've been wondering a lot about why Python handles classes and OOP the
> way it does. From what I understand, there is no concept of class
> encapsulation in Python, i.e. no such thing as a private variable. Any
> part of the code is allowed access to any variable in any class, and
> even non-existant variables can be accessed: they are simply created.
> I'm wondering what the philosophy behind this is, and if this
> behaviour is going to change in any future release of Python.

There are advantages and disadvantages to C++/Java style encapsulation 
using private data.  The advantages you (apparently) already know.  The 
disadvantage is added complexity.  There's a saying, "You can't have a bug 
in a line of code you never write".  By having to write all those getter 
and setter methods, you just add bulk and complexity.

That being said, you can indeed have private data in Python.  Just prefix 
your variable names with two underscores (i.e. __foo), and they effectively 
become private.  Yes, you can bypass this if you really want to, but then 
again, you can bypass private in C++ too.   You can also intercept any 
attempt to access Python attributes by writing __getattr__() and 
__setattr__() methods for your class.

> It seems to me that it is difficult to use OOP to a wide extent in
> Python code because these features of the language introduce many
> inadvertant bugs. For example, if the programmer typos a variable name
> in an assignment, the assignment will probably not do what the
> programmer intended.

Yes, that is is a risk.  Most people deal with that risk by doing a lot of 
testing (which you should be doing anyway).  If you really want to, you can 
use the __slots__ technique to prevent this particular bug from happening 
(although the purists will tell you that this is not what __slots__ was 
designed for).

> My main question is that of why Python chooses to use this type of OOP 
> model and if it is planned to change.

It sounds like you are used to things like C++ and Java, which are very 
static languages.  Everything is declared at compile time, and there are 
many safeguards in the language to keep you from shooting yourself in the 
foot.  They problem is, they often prevent you from getting any useful work 
done either; you spend most of your time programming the language, not the 
problem you are trying to solve.

In the past week, I've had two conversations with people about the nuances 
of C++ assignment operators.  None of our customers give two figs about 
assignment operators.  Getting them right is just a detour we need to take 
to keep our software from crashing.  With Python, I write a = b and trust 
that it does the right thing.  That lets me concentrate on adding value 
that our customer will see.



More information about the Python-list mailing list