How to “hide” superclass methods in a subclass

半世苍凉 提交于 2019-12-05 08:46:57

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)

You should not subclass then, you should use composition. Wrap your other class instance in a new class instance and use as necessary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!