Implementing class attribute access methods via pseudo-functi on o verloading.

Alex Martelli aleaxit at yahoo.com
Tue Oct 26 08:17:08 EDT 2004


<Doran_Dermot at emc.com> wrote:
   ...
> It's interesting to note that you prefer code like: theProblem.title = "The
> Title"
> 
> However, I wonder if people coming from the Java/C++ world prefer:
> theProblem.title( "The Title" )
> 
> Obviously the first version is less typing! However, the second version
> might feel more natural to Java/C++ programmers.  Just an observation!

If you want to accomodate Java crazies (with setFoo/getFoo manias,
universal there) you might...:

>>> class x(object):
...   def __getattr__(self, name):
...     if name.startswith('get') and name[3:4].isupper():
...        n = name[3:4].lower() + name[4:]
...        return lambda: getattr(self, n)
...     raise AttributeError, name

and whatever else.  Now, you can read any attribute of instances of x
with that silly syntax to your heart's contents.  E.g.:

c = x()
c.foo = 23
print c.getFoo()

There!  The ULTIMATE Java-Python bridge.  Now, at last, nothing will
impede Python from vying for the hearts and minds of Javaites.  (BTW: it
works just fine with properties, too).

The extension of this idea to methods such as setFoo is left as an
exercise to the reader, as is the trivial optimization of caching the
lambda into self, just in case it's repeatedly called.


Alex



More information about the Python-list mailing list