Accessors in Python (getters and setters)
Steve Holden
steve at holdenweb.com
Thu Jul 20 03:15:33 EDT 2006
mystilleef wrote:
[...]
>
> I don't know it's your code not mine.
>
> class Robust(object):
>
> def __init__(self):
> # Arbitrarily changing this state to False will crash app or will
> # corrupt the whole event system.
> self.__is_active = True
>
> def get_is_active(self):
> return self.__is_active
>
> buffer_is_active = property(get_is_active, doc="True if buffer is
> editable")
>
Let's ignore changes of state for the moment. The mystical difference
that makes read access via
some_robust.buffer_is_active()
acceptable and
some_robust.__is_active
somehow dangerous (ignoring the fact that name_mangling will take place)
is what?
> def monitor_events(self):
> # Only methods of this class can change __is_active.
> # Add code to change __is_active here.
> return
>
I'm sure nobody would argue that if close synchronization between
multiple attributes is required then write accessors are a bad idea. But
using them unnecessarily just makes your code heavier, slower and less
easy to maintain.
> See! I'm controlling access. Whee! And if one sober morning I want to
> change the name __is_active to __buffer_is_active, I won't have to hunt
> down 27000 lines of code to do it. Also a naive third party won't crash
> my system by changing Robust's state arbitrarily. Because in the real
> world when your program is buggy, you get bug reports, nasty emails
> among other forms of ridicule. And your supposed solution to my problem
> is me saying, "but...but...I told you not change is_active." Ha! And if
> you can't figure out why anyone would do this, then I'm not wasting my
> time here anymore. Someday you'll learn the hard way.
>
It's way too late. My comments *are* based on engineering experience.
One day you may realise that unnecessary complexity is a far bigger time
waster than any imagined problems of direct attribute access. I suspect
that if you are getting complaints if the nature you describe it's just
because your software isn't that good.
> Thanks to the people who exposed me to Python's properties.
>
> Bye
>
Really? Promise? I fear we are arguing from different premises.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list
mailing list