How to "hide" superclass methods in a subclass

Basically, I want to create a subclass that β€œhides” the methods in the superclass so that they do not appear in the dir() or hasattr() call, and users cannot call them (at least not through any of the normal channels). I would also like to do this with the least amount of β€œmagic”. Thanks.

+4
source share
2 answers

The priority of the __dir__ and __getattribute__ should do the trick. This is pretty much a canonical way to do this stuff in Python. Although it is important that you actually do this, this is a completely different matter.

See Python Docs in Setting Attribute Access

Use __dir__ to display the available attributes (this will not affect access to the actual attribute)

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

Use __getattribute__ to control access to the actual attribute

 class A(object): def __getattribute__(self, attr): """Prevent 'private' attribute access""" if attr.startswith('_'): raise AttributeError return object.__getattribute__(self, attr) >>> a = A() >>> ax = 5 >>> ax 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) 
+6
source

Then you should not subclass, you should use composition. Wrap an instance of another class in an instance of a new class and use as needed.

+3
source

All Articles