Python style of accessing bools?
Roy Smith
roy at panix.com
Thu Apr 15 10:15:44 EDT 2004
In article <mailman.650.1082035141.20120.python-list at python.org>,
Jonathon McKitrick <jcm at FreeBSD-uk.eu.org> wrote:
> I'm trying to avoid leftover C-style in my new Python programs.
>
> If a class has a boolean property, and I am branching based on that
> property, which of these is preferred?
>
> if MyClass.boolProp:
> <continue>
>
> OR
>
> if MyClass.IsTrueProp():
> <continue>
>
> In other words, do you use accessors or just access the variable directly?
>
> jm
My general habit is to avoid accessor functions and grab the value
directly. It's just simplier. Writing accessor functions is (IMHO)
just mindless busywork, and more code that can break (Yes, I've written
accessor functions which had bugs!)
If you read up on the __getattr__() stuff, you'll discover that
accessing the attribute may actually end up calling a user-defined
function anyway, which may set your thoughts about private data on its
ear.
The classic argument for private data and public accessor functions is
that you can change the underlying data store and keep the interface the
same. It turns out you can do the same thing in Python with
__getattr__(). If you need to change the way the data is stored, you
can delete the attribute from your object, catch references to the (now,
non-existant) attribute with __getattr__(), and continue to export the
same interface you did before.
More information about the Python-list
mailing list