[Tutor] Hiding Superclass Methods

Alan Gauld alan.gauld at btinternet.com
Mon Oct 11 10:13:00 CEST 2010

"Denis Gomes" <denisg640 at gmail.com> wrote

>   I have a basic python question.  I am writing an n dimensional 
> vector
> class by inheriting from the builtin python list object.  I want to 
> be
> able to hide the parent object's methods in the derived class 
> instances.

Doing so would break the Liskofff Substitution Principle which says
you should be able to use your subclass anywhere that the parent
class can be used. This is a very bad thing!

If you want to expose a reduced set of operations, rather than an
extended set, then inheritance is the wriong solution. You should
consider using delegation instead. Create a list indside your class
and forward any requests for the operations you do want to the
list object.

The only snag with delegation in this scenartio is that you have
to write an awful lot of one-liner methods. To get round that
you can use setattr() and getattr() combined with a list of allowed
operation names. Check the operation is in the list and then
forward the request by name. That can save a lot of coding!


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list