Is there a way to 'mask out' inherited methods?
Alex Martelli
aleax at aleax.it
Fri May 3 03:41:17 EDT 2002
Ralf Juengling wrote:
...
> I'm fiddling around with some new 2.2.-features. I want to
> inherit from a builtin-type but want to use only a subset
> of its functionality:
>
> class Vector(list):
...
> I.e. Vector should keep or inherit methods meaningful to vectors
> (e.g. '__str__', '__getitem__', '__cmp__' and so on), and should
> somehow undefine or mask out any methods not meaningful to it
> ('append', 'reverse', ..).
>
> Any idea how to achieve that easily?
"Easily" within the constraints you stated, only one way: add a
__getattribute__ method that selects only the attributes (note that
methods are also attributes) you want to expose, e.g.:
class Vector(list):
mymethods = '__str__', '__getitem__', '__cmp__'
def __getattribute__(self, name):
if name in self.mymethods:
return object.__getattribute__(self, name)
else: raise AttributeError, name
Forget *SPEED*, of course -- when you define __getattribute__
Python calls it for EVERY attribute request, so your code will just
crawl. For speed, your choice is: either drop the constraint that
Vector must subclass list, and delegate instead; or, if the constraint
MUST be kept, override all methods you want to 'mask out' and
have each of them raise AttributeError (not quite the same thing,
of course -- getattr would still 'see' them, for example). A custom
metaclass might help (not trivial).
My advice: forget subclassing when you don't want to expose all
of the parent-class interface -- use delegation instead.
Alex
More information about the Python-list
mailing list