OO in Python? ^^

Alex Martelli aleax at mail.comcast.net
Sun Dec 11 12:50:48 EST 2005

Matthias Kaeppler <void at void.com> wrote:
> I stumbled over this paragraph in "Python is not Java", can anyone 
> elaborate on it:
> "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."
> Why would I want to use an attribute in Python, where I would use 
> getters and setters in Java? I know that encapsulation is actually just
> a hack in Python (common, "hiding" an implementation detail by prefixing
> it with the classname so you can't access it by its name anymore? Gimme
> a break...), but is that a reason to only write white box classes? ^^

Consider the difference between asking a user of your class to write:

a.setFoo(1 + a.getFoo())

versus allowing him or her to write:

a.foo += 1

I hope you can see how much more elegant and handy the second
alternative is.  The point is, in Python, you can easily make the
semantics of the second alternative identical to those of the first: all
you need to do is, within a's class, add ONE line:
    foo = property(getFoo, setFoo)
and every access of a.foo will become a call to a.getFoo(), every
setting of a.foo=bar a call to a.setFoo(bar).

The ability to do this IF AND WHEN getFoo and setFoo really need to
exist (i.e., they do something meaningful, not just boilerplate setting
and getting of plain attributes) empowers you to always allow the users
of your class to access attributes -- you will change an attribute to a
property only in future versions of your class that do need some
meaningful action upon the getting or setting or that attribute.


More information about the Python-list mailing list