object.attribute vs. object.getAttribute()

John Roth newsgroups at jhrothjr.com
Mon Sep 15 22:15:49 EDT 2003


"Roy Smith" <roy at panix.com> wrote in message
news:roy-81B3E5.20291015092003 at reader2.panix.com...
> For the past 6-8 months, I've spent most of my time writing C++ and a
> little bit of Java.  Both of these languages support and encourage the
> use of private data and explicit accessor functions, i.e. instead of
> writing x = foo.bar, you write x = foo.getBar().  Now that I'm back to
> writing Python, I find myself in a quandry.
>
> Historically, I've always avoided accessor functions and just reached
> directly into objects to get the value of their attributes.  Since
> Python doesn't have private data, there really isn't much advantage to
> writing accessors, but somehow I'm now finding that it just feels wrong
> not to.  I'm not sure if this feeling is just a C++/Java-ism that will
> cure itself with time, or if perhaps it really does make sense and I
> should change the way I code.

I'm with Jeff on this one. If it looks like a value, then access it
directly.
If you need to slide a mutator in under it, it's simple enough to make
it a property later without affecting any of the code that uses it.


> On the plus side, accessors/mutators give me:
>
> 1) Implicit documentation of which attributes I intended to be part of
> an object's externally visible state (accessors).

Use the underscore convention.

> 2) Hooks to do data checking or invarient assertions (mutators).
> 3) Decoupling classes by hiding the details of data structures.
> 4) Vague feeling that I'm doing a good thing by being more in line with
> mainstream OO practices :-)

4 is actually the same thing as 3, except not stated as cleanly.

> On the minus side:
>
> 1) More typing (which implies more reading, which I think reduces the
> readability of the finished product).
> 2) Need to write (and test) all those silly little functions.
> 3) Performance hit due to function call overhead.
> 4) Only the appearance of private data (modulo some slots hackery).
> 5) Code is harder to change (adding functionality means going back and
> adding more slots).
> 6) Vague feeling that I'm dirtying myself by letting C++ and Java change
> my Python coding habits :-)

Items 1 through 3 don't matter if you use properties. You use them when
you need them, otherwise you simply access the attribute directly.

If you're using Python, you don't worry about private data. Use the
underscore convention, and don't worry otherwise.

Don't use slots.

I never worry about where a good idea comes from.

John Roth
>
> Comments?






More information about the Python-list mailing list