A matter of style: class.foo = bar vs. class.set_foo(bar)

Alex Martelli aleaxit at yahoo.com
Sat Nov 11 11:23:43 EST 2000


<echuck at mindspring.com> wrote in message news:8ujpft$4at$1 at nnrp1.deja.com...
    [snip]
> The disadvantage of:
>   obj.foo = 5
>
> is that in the future if you want to take some action when foo is set,
> like asserting that it's in range or not None, then you're out of luck.

Naah -- you just have to add a __setattr__ method (or a clause to
your existing __setattr__ method); or, with suitable metaclasses
(such as those in py_cpp), you even get to define a specific
__setattr__foo method to catch the specific setting of obj.foo only.

You may still choose, as a matter of style, to impose the use of
.setFoo or whatever, but it's also a possibility, of equal functional
ability, to let client-code use the more-natural-to-some syntax
    obj.foo = 5
rather than
    obj.setFoo(5)

Worst case, you'll trade off a tiny bit more of programming in
the class (if you're not using suitable metaclasses) for a bit
more convenience for the client!  Remember that, if you let
the assignment operator be used by the client, he then can,
"for free" (no extra coding needed on your part...):
    obj.foo += 5
and
    obj.foo *= 2
etc etc, rather than having to write
    obj.setFoo(obj.getFoo() * 2)
etc.  It's surely a feasible style choice to enable this.

This is Python, remember... how can you be out of luck, when
to be using Python is already such a happy state?-)


Alex






More information about the Python-list mailing list