Less APIs or more encapsulation?
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Thu Sep 10 03:07:34 EDT 2009
Tycho Andersen a écrit :
> On Wed, Sep 9, 2009 at 10:08 AM, 一首诗<newptcai at gmail.com> wrote:
>> But when C has many many methods to expose to outer user, 2nd choice
>> seems to be more reasonable I In the first design, B.newMethod did
>> nothing really useful.
>
> Is there any reason you can't do something like the following?
>
> class B(object):
> def __init__(self, c):
> self.__c = c;
There are very few real use case for the name-mangling '__name' scheme,
and this is probably not one. A single leading underscore should be enough.
> def __getattr__(self, name):
> return self.__c.__getattribute__(name)
__magic_methods__ are implementation support for operators and
operator-like generic functions (len() etc). The good practice is to use
the operator or generic function, not to directly call the
implementation __method__.
Also, since it's about encapsulation, it would be better to also hide
the delegation:
def __getattr__(self, name):
try:
return getattr(self._c, name)
except AttributeError:
msg = "'%s' object as no attribute '%s'"
raise AttributeError(msg % (type(self), name)
More information about the Python-list
mailing list