Reputation:
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.
Upvotes: 8
Views: 3313
Reputation: 90999
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)
Upvotes: 7
Reputation: 43024
You should not subclass then, you should use composition. Wrap your other class instance in a new class instance and use as necessary.
Upvotes: 6