Alex Rivera | Logout

How to "hide" superclass methods in a subclass

Asked 2011-04-29T02:39:31.853
9

I basically want to create a subclass that "hides" methods on the superclass so that they don't show up in a dir() or hasattr() call and the users can't call them (at least not through any of the normal channels). I would also like to do this with the least amount of "magic" possible. Thanks.

Edit
Report

1 Answer

7

Overriding the __dir__ and __getattribute__ method respectively should do the trick. This is the pretty much the canonical way to do this kind of stuff in Python. Although whether you should be actually doing this is entirely a different matter.

See Python docs on Customizing Attribute Access

Use __dir__ to list available attributes (this won't affect actual attribute access)

class A(object):
    def __dir__(self):
        return []

>>> print dir(A())
[]

Use __getattribute__ to control actual attribute access

class A(object):
    def __getattribute__(self, attr):
        """Prevent 'private' attribute access"""
        if attr.startswith('_'):
            raise AttributeError

        return object.__getattribute__(self, attr)


>>> a = A()
>>> a.x = 5
>>> a.x
5
>>> a._x = 3
>>> a._x
AttributeError

This is probably what you are trying to do.

class NoSuper(object):
    def __getattribute__(self, attr):
        """Prevent accessing inherited attributes"""
        for base in self.__bases__:
            if hasattr(base, attr):
                raise AttributeError

        return object.__getattribute__(self, attr)
answered 2011-04-29T02:40:49.970

Your Answer