This is the second article following up Phillip J. Eby's Python Is Not
Java. In the first article, The Static Method Thing, we took
a look at how Java static methods differ from Python class/static methods. This
time we're going to dive deep into the evils of getters and setters.
I'm hopping around a bit because this was the item that I saw the most
confusion around in comments and trackback posts. I'm also a bit worried that
some walked away with the impression that getters and setters are always evil
and should never be used, ever, in any language, ever. Getters and
setters are not GOTOs, and Phillip's original post never came close to making
that claim.
Let's take a look at what Phillip had to say about getters and setter use in
Python:
Getters and setters are evil. Evil, evil, I say! Python objects are not Java
beans. Do not write getters and setters. This is what the 'property' built-in
is for. And do not take that to mean that you should write getters and
setters, and then wrap them in 'property'. That means that until you prove
that you need anything more than a simple attribute access, don't write
getters and setters. They are a waste of CPU time, but more important, they
are a waste of programmer time. Not just for the people writing the code and
tests, but for the people who have to read and understand them as well.
In Java, you have to use getters and setters because using public fields
gives you no opportunity to go back and change your mind later to using
getters and setters. So in Java, you might as well get the chore out of the
way up front. In Python, this is silly, because you can start with a normal
attribute and change your mind at any time, without affecting any clients of
the class. So, don't write getters and setters.
I thought he explained this well. There's not a lot missing here so I'm going
to dive real deep and try to give a lot of background and code examples on the
situation.