When is a subclass not right?

David Ells ells.david at gmail.com
Fri Aug 25 14:56:51 EDT 2006


Chaz Ginger wrote:
> I was writing some code that used someone else class as a subclass. He
> wrote me to tell me that using his class as a subclass was incorrect. I
> am wondering under what conditions, if ever, does a class using a
> subclass not work.
>
> Here is an example. For instance the original class might look like:
>
> class A :
>   def __init__(self,arg) :
> 	self.foo = arg
>   def bar(self) :
> 	return self.foo
>
>
> And I defined a class B1 which looked like:
>
>
> class B1(A);
>   def __init__(self,a1,a2) :
> 	self.c = a1
> 	A.__init__(self,ag)
>
>
> He said I should use it this way:
>
> class B2:
>   def __init__(self,a1,a2):
> 	self.c = a1
> 	self.t = A(a2)
>
>   def bar(self) :
> 	self.t.bar()
>
>
> Other than the obvious difference of B2 having an attribute 't', I can't
> see any other obvious differences. Is there something I am missing?
>
> TIA
> Chaz

This is also known as White Box inheritance vs. Black Box inheritance,
or inheritance vs. composition, although it doesn't necessarily have
the same full implications in Python (since private variables and
methods of a class can still be accessed without much trouble, in any
code, not just the subclass). In defining a class with built in
language inheritance (i.e. class B1(A)), all the private variables and
methods of the super class are exposed to the base class, so the
subclass can use details of the implementation of the super class in
its own implementation. Make sense? This is white box inheritance, i.e.
everything is exposed to the subclass. The other, Black Box
inheritance, happens when the "subclass" contains an instance of the
super class. Then the subclass will use delegation to expose the
methods of the super class (or override them, add to them, etc). This
black box style is more sound in terms of abstraction and modularity,
as white box inheritance usually leads to more implementation
dependencies between the subclass and super class (which can break the
subclass when the super class implementation changes), while black box
inheritance uses the interface of the super class to interact with it
(hence allowing you to replace the super class of the subclass with any
class that has the same interface). However, in the black box style, it
can be a pain to update the interface of the sub class every time you
add some other functionality to the super class, i.e. if you create a
new method in A called foo2(), it would automatically be accessible in
B1, but you have to create a new method also called foo2() in B2 that
delegates to A.




More information about the Python-list mailing list