OOP / language design question

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Apr 25 19:52:22 EDT 2006


Duncan Booth a écrit :
> bruno at modulix wrote:
> 
> 
>>class Base(object):
>>  def __init__(self, arg1):
>>    self.attr1 = arg1
>>    self.dothis()
>>
>>  def dothis(self):
>>    return self.attr1
>>
>>class Derived(Base):
>>  def __init__(self, arg1, arg2=0):
>>    self.attr2 = arg2
>>    Base.__init__(self, arg1)
>>
>>  def dothis(self):
>>    return self.attr1 + self.attr2
>>
>>(snip)
>>
>>
>>>Perhaps if the base __init__ calls an overridden 
>>>method, but at that point it sounds to me like something wants
>>>refactoring. 
>>
>>Why so ? This is a well-known pattern (template method). I don't see
>>what's wrong with it.
> 
> 
> Apart from the fact that you can delete the method 'dothis' from both 
> classes with no effect on the code?

Mmmm... Oh, I see. Agreed, this is not a very good example.

 >>class Base(object):
>>  def __init__(self, arg1):
>>    self.attr1 = arg1
>>    self.attr42 = self.dothis()

Is that better ?-)

Ok, let's be serious now...

> 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.

> 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.

I don't have any concrete example at hand, but I can tell you I've done 
such things often enough.

> 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

I'm afraid I fail to see what's so special about 'virtual' methods - and 
FWIW, since all methods in Python are virtual, if you don't want to call 
virtual methods in the initializer, you won't get very far !-)

> 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.

What if some of the things one have to do at initialization is also used 
elsewhere ? You would not duplicate code, would you ?



More information about the Python-list mailing list