覆盖__dir__
and __getattribute__
方法分别应该可以解决问题。这几乎是在 Python 中执行此类操作的规范方法。尽管您是否应该真正这样做完全是另一回事。
请参阅 Python 文档自定义属性访问 http://docs.python.org/reference/datamodel.html#customizing-attribute-access
Use __dir__
列出可用属性(这不会影响实际的属性访问)
class A(object):
def __dir__(self):
return []
>>> print dir(A())
[]
Use __getattribute__
控制实际属性访问
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
这可能就是您正在尝试做的事情。
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)