[Q] Accessors...
Greg Ewing
greg.ewing at compaq.com
Mon Jul 19 17:46:42 EDT 1999
Olivier Deckmyn wrote:
>
> This way, because it exists two methods get_XXX and set_XXX, a special
> proporty XXX would be implicitly created, and would make the user call
> "automatically" the get/set methods.
Yes, there is a way. If a class has a method
called __getattr__, it is automatically called
whenever you try to get the value of an attribute
which doesn't exist. So you can do something like
class AutoAccess:
def __getattr__(self, name, *args, **kw):
return apply(getattr(self, "get_"+name), args, kw)
then any class which inherits from AutoAccess will
have any attempt to get a non-existent XXX attribute
redirected to a get_XXX method. (Note that the above
implementation is a bit simplistic -- it will enter an
infinite loop if there is no get_XXX method defined
in the class.)
There is a corresponding feature for setting an
attribute: if there is a __setattr__ method, it gets
called on every attempt to set the value of an
attribute, so you can do
def __setattr__(self, name, value):
try:
setter = getattr(self, "set_"+name)
except AttributeError:
setter = None
if setter:
setter(value)
else:
self.__dict__[name] = value
This is more complicated because the __setattr__
method, if present, is called *before* checking
whether the attribute exists (by necessity, since
setting an attribute which doesn't already exist
is perfectly legal). Hence the code to catch the
case where there is no set_XXX method and set the
attribute directly.
As you can see, what you are asking for can be
done, but it is expensive -- attribute access
through these methods will be considerably slower
than just calling get_XXX and set_XXX methods
directly. You'll have to decide whether it's
worth the price in your application.
Warning: The above code is for illustration
purposes only -- I haven't tested it!
Greg
More information about the Python-list
mailing list