A matter of style: class.foo = bar vs. class.set_foo(bar)
echuck at mindspring.com
echuck at mindspring.com
Mon Nov 13 23:50:33 EST 2000
In article <8ujrso02bef at news1.newsguy.com>,
"Alex Martelli" <aleaxit at yahoo.com> wrote:
> <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.
Although it's technically feasible to do a __setattr__, what would the
results look like for foo, bar, a, b, c?
if name=="foo":
do_this()
elif name=="bar":
do_that()
elif name=="...
You get the drift. This is really inefficient. Every time you add a new
attribute you increase this linear search and pile on more code in
__setattr__. I suppose you could do this:
methodName = "set_"+name
method = getattr(self, methodName, None)
if method:
method(name, value)
else:
self.__dict__[name] = value
But it feels silly to make setattr to call set_foo() for you...maybe
I'm just not use to it.
I can't say I'm familiar with the metaclasses you refer to. Care to
expand with an example in this context?
> 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.
Well, I don't use "get", so it would be shorter. :-)
Also, my attributes are hardly ever numeric. They are usually other
objects, strings, lists, dictionaries, etc.
-Chuck
--
Webware for Python:
http://webware.sourceforge.net
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list