OOP / language design question

Alex Martelli aleaxit at yahoo.com
Wed Apr 26 00:15:31 EDT 2006


Duncan Booth <duncan.booth at invalid.invalid> wrote:
   ...
> Actually, this is quite an interesting example becaue it wouldn't work in
> C++: if you tried the same trick the call to dothis from the base 
> constructor (even assuming it is virtual) would actually call Base.dothis.

Yep.

> I think you have demonstrated that you can do some things in Python which
> you simply cannot do in static languages like C++: assigning to derived
> attributes before calling a base initialiser, and calling a virtual method
> from a base initialiser. I'm not arguing about that. What I don't have
> though is an example of code where doing this would actually be a good
> thing.

A recognized idiom/pattern in C++ or Java is known as "two-phase
construction" (yes, there's a two-phase destruction counterpart): have
minimal, near-empty constructors, then a separate virtual Init method
which does the actual construction work (often with a framework or at
least a factory to ensure that Init gets in fact called).

Each use case of this idiom/pattern relies on virtual methods (most
generally in a Template Method design pattern) at initialization.

E.g.: build a composite window by iteratively building subwindows
(including decorators) as enumerated by a virtual method.  Initialize a
database-connection object by delegating some parts (such as connection,
local or over the net, and authentication, etc etc) to virtual methods.
And so on, and so forth.


> What I think I'm trying to get at is that I believe that most situations
> where someone actually tries to do something in the base initialiser which
> requires calling a virtual method are probably also cases where the 
> initialiser is doing too much: i.e. separating the 
> construction/initialisation from actually doing something is usually a good
> idea.

But why should that be?  Template Method is perhaps the MOST generally
useful design pattern -- why would it be any less useful in
initialization than elsewhere?!


Alex



More information about the Python-list mailing list